import React, { useState } from 'react';
import { Alert, ScrollView, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../context/AppContext';
import { Button } from '../components/ui/Button';
import { Input } from '../components/ui/Input';
import { RootStackParamList } from '../navigation/types';

export default function AuthRegister() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const { register } = useApp();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<'cliente' | 'barbearia'>('cliente');
  const [shopName, setShopName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async () => {
    setError('');
    if (!name.trim()) return setError('Preencha o nome completo');
    if (!email.trim()) return setError('Preencha o email');
    if (!password.trim()) return setError('Preencha a palavra-passe');
    if (role === 'barbearia' && !shopName.trim()) return setError('Informe o nome da barbearia');

    try {
      setLoading(true);
      const nextUser = await register({
        name: name.trim(),
        email: email.trim(),
        password,
        role,
        shopName: shopName.trim(),
      });

      if (!nextUser) {
        Alert.alert('Conta criada', 'Confirma o email antes de fazer login.');
        navigation.replace('Login');
        return;
      }
    } catch (e: any) {
      const message = e?.message || 'Erro ao criar conta';
      setError(message);
      Alert.alert('Erro', message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <View style={styles.logoRow}>
          <Image 
            source={require('../../assets/logo.png')} 
            style={styles.logoImage} 
            resizeMode="contain"
          />
        </View>

        <Text style={styles.title}>Criar Conta</Text>
        <Text style={styles.subtitle}>Junte-se à Smart Agenda</Text>

        {!!error && (
          <View style={styles.errorBox}>
            <Text style={styles.errorText}>{error}</Text>
          </View>
        )}

        <Text style={styles.label}>Eu sou...</Text>
        <View style={styles.roleContainer}>
          {(['cliente', 'barbearia'] as const).map((item) => (
            <TouchableOpacity
              key={item}
              style={[styles.roleButton, role === item && styles.roleButtonActive]}
              onPress={() => { setRole(item); setError(''); }}
            >
              <Text style={[styles.roleEmoji]}>{item === 'cliente' ? '✂️' : '💈'}</Text>
              <Text style={[styles.roleText, role === item && styles.roleTextActive]}>
                {item === 'cliente' ? 'Cliente' : 'Barbearia'}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        <Input label="Nome completo" value={name} onChangeText={setName} placeholder="Ex: João Silva" />
        <Input
          label="Email"
          value={email}
          onChangeText={(text) => { setEmail(text); setError(''); }}
          keyboardType="email-address"
          autoCapitalize="none"
          placeholder="exemplo@email.com"
        />
        <Input label="Palavra-passe" value={password} onChangeText={setPassword} secureTextEntry placeholder="••••••••" />

        {role === 'barbearia' && (
          <Input
            label="Nome da barbearia"
            value={shopName}
            onChangeText={setShopName}
            placeholder="Ex: Barbearia Estilo"
          />
        )}

        <Button onPress={handleSubmit} style={styles.submitButton} loading={loading}>
          Criar minha conta
        </Button>

        <View style={styles.divider} />

        <View style={styles.footer}>
          <Text style={styles.footerText}>Já tem uma conta? </Text>
          <Text style={styles.footerLink} onPress={() => navigation.navigate('Login')}>
            Fazer Login
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a0a0f',
  },
  content: {
    padding: 24,
    justifyContent: 'center',
    minHeight: '100%',
  },
  logoRow: {
    alignItems: 'center',
    marginBottom: 28,
  },
  logoImage: {
    width: 200,
    height: 100,
  },
  title: {
    fontSize: 34,
    fontWeight: '900',
    color: '#f8fafc',
    textAlign: 'center',
    marginBottom: 6,
  },
  subtitle: {
    fontSize: 15,
    color: '#64748b',
    marginBottom: 28,
    textAlign: 'center',
    fontWeight: '500',
  },
  errorBox: {
    backgroundColor: 'rgba(239,68,68,0.1)',
    borderColor: 'rgba(239,68,68,0.3)',
    borderWidth: 1,
    borderRadius: 14,
    padding: 14,
    marginBottom: 16,
  },
  errorText: {
    color: '#fca5a5',
    fontWeight: '600',
    fontSize: 13,
  },
  label: {
    fontSize: 12,
    color: '#94a3b8',
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 10,
  },
  roleContainer: {
    flexDirection: 'row',
    gap: 12,
    marginBottom: 20,
  },
  roleButton: {
    flex: 1,
    padding: 18,
    borderRadius: 16,
    borderWidth: 1.5,
    borderColor: 'rgba(255,255,255,0.06)',
    backgroundColor: '#141420',
    alignItems: 'center',
    gap: 8,
  },
  roleButtonActive: {
    borderColor: '#6366f1',
    backgroundColor: 'rgba(99,102,241,0.1)',
  },
  roleEmoji: {
    fontSize: 24,
  },
  roleText: {
    fontSize: 13,
    fontWeight: '800',
    color: '#64748b',
    textTransform: 'uppercase',
  },
  roleTextActive: {
    color: '#a5b4fc',
  },
  submitButton: {
    width: '100%',
    marginTop: 4,
    backgroundColor: '#6366f1',
    paddingVertical: 16,
  },
  divider: {
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.06)',
    marginVertical: 24,
  },
  footer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
  },
  footerText: {
    fontSize: 14,
    color: '#64748b',
  },
  footerLink: {
    fontSize: 14,
    color: '#818cf8',
    fontWeight: '800',
  },
});
