import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  SafeAreaView,
  ScrollView,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { colors, fonts, spacing, borderRadius, shadows } from '../../config/theme';
import { entregadorAPI } from '../../config/api';

const VEICULOS = [
  { id: 'moto', nome: 'Moto', icon: '🏍️' },
  { id: 'carro', nome: 'Carro', icon: '🚗' },
  { id: 'van', nome: 'Van', icon: '🚐' },
  { id: 'caminhao', nome: 'Caminhão', icon: '🚛' },
];

export default function CadastroScreen({ navigation }) {
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  
  // Dados pessoais
  const [nome, setNome] = useState('');
  const [email, setEmail] = useState('');
  const [telefone, setTelefone] = useState('');
  const [cpf, setCpf] = useState('');
  const [senha, setSenha] = useState('');
  
  // Dados do veículo
  const [veiculo, setVeiculo] = useState('moto');
  const [placa, setPlaca] = useState('');
  const [marca, setMarca] = useState('');
  const [modelo, setModelo] = useState('');

  const formatarTelefone = (text) => {
    const cleaned = text.replace(/\D/g, '');
    let formatted = cleaned;
    if (cleaned.length >= 2) {
      formatted = `(${cleaned.slice(0, 2)}) ${cleaned.slice(2)}`;
    }
    if (cleaned.length >= 7) {
      formatted = `(${cleaned.slice(0, 2)}) ${cleaned.slice(2, 7)}-${cleaned.slice(7, 11)}`;
    }
    return formatted;
  };

  const formatarCPF = (text) => {
    const cleaned = text.replace(/\D/g, '');
    let formatted = cleaned;
    if (cleaned.length >= 3) {
      formatted = `${cleaned.slice(0, 3)}.${cleaned.slice(3)}`;
    }
    if (cleaned.length >= 6) {
      formatted = `${cleaned.slice(0, 3)}.${cleaned.slice(3, 6)}.${cleaned.slice(6)}`;
    }
    if (cleaned.length >= 9) {
      formatted = `${cleaned.slice(0, 3)}.${cleaned.slice(3, 6)}.${cleaned.slice(6, 9)}-${cleaned.slice(9, 11)}`;
    }
    return formatted;
  };

  const validarStep1 = () => {
    if (!nome || !email || !telefone || !cpf || !senha) {
      Alert.alert('Erro', 'Preencha todos os campos');
      return false;
    }
    if (senha.length < 6) {
      Alert.alert('Erro', 'A senha deve ter pelo menos 6 caracteres');
      return false;
    }
    return true;
  };

  const handleCadastro = async () => {
    if (!placa) {
      Alert.alert('Erro', 'Informe a placa do veículo');
      return;
    }

    setLoading(true);
    try {
      const dados = `nome=${encodeURIComponent(nome)}&email=${encodeURIComponent(email)}&telefone=${encodeURIComponent(telefone)}&cpf=${encodeURIComponent(cpf)}&senha=${encodeURIComponent(senha)}&veiculo=${veiculo}&placa=${encodeURIComponent(placa)}&marca=${encodeURIComponent(marca)}&modelo=${encodeURIComponent(modelo)}`;
      
      const response = await entregadorAPI.cadastro(dados);
      
      if (response.data.success) {
        Alert.alert(
          'Cadastro Enviado! 🎉',
          'Seu cadastro foi enviado para análise. Você receberá um email quando for aprovado.',
          [{ text: 'OK', onPress: () => navigation.goBack() }]
        );
      } else {
        Alert.alert('Erro', response.data.message || 'Erro ao realizar cadastro');
      }
    } catch (error) {
      Alert.alert('Erro', 'Não foi possível conectar ao servidor');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity onPress={() => step === 1 ? navigation.goBack() : setStep(1)}>
            <Text style={styles.backButton}>← Voltar</Text>
          </TouchableOpacity>
          <Text style={styles.title}>Seja um Entregador</Text>
          <Text style={styles.subtitle}>Etapa {step} de 2</Text>
          
          {/* Progress Bar */}
          <View style={styles.progressBar}>
            <View style={[styles.progressFill, { width: step === 1 ? '50%' : '100%' }]} />
          </View>
        </View>

        {/* Formulário */}
        <View style={styles.form}>
          {step === 1 ? (
            <>
              <Text style={styles.formTitle}>Dados Pessoais</Text>
              
              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>👤</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Nome completo"
                  placeholderTextColor={colors.gray[400]}
                  value={nome}
                  onChangeText={setNome}
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>📧</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Email"
                  placeholderTextColor={colors.gray[400]}
                  value={email}
                  onChangeText={setEmail}
                  keyboardType="email-address"
                  autoCapitalize="none"
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>📱</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Telefone"
                  placeholderTextColor={colors.gray[400]}
                  value={telefone}
                  onChangeText={(text) => setTelefone(formatarTelefone(text))}
                  keyboardType="phone-pad"
                  maxLength={15}
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>🪪</Text>
                <TextInput
                  style={styles.input}
                  placeholder="CPF"
                  placeholderTextColor={colors.gray[400]}
                  value={cpf}
                  onChangeText={(text) => setCpf(formatarCPF(text))}
                  keyboardType="numeric"
                  maxLength={14}
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>🔒</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Senha"
                  placeholderTextColor={colors.gray[400]}
                  value={senha}
                  onChangeText={setSenha}
                  secureTextEntry
                />
              </View>

              <TouchableOpacity
                style={styles.button}
                onPress={() => validarStep1() && setStep(2)}
              >
                <Text style={styles.buttonText}>Próximo →</Text>
              </TouchableOpacity>
            </>
          ) : (
            <>
              <Text style={styles.formTitle}>Dados do Veículo</Text>
              
              <Text style={styles.label}>Tipo de Veículo</Text>
              <View style={styles.veiculosGrid}>
                {VEICULOS.map((v) => (
                  <TouchableOpacity
                    key={v.id}
                    style={[
                      styles.veiculoCard,
                      veiculo === v.id && styles.veiculoCardSelected,
                    ]}
                    onPress={() => setVeiculo(v.id)}
                  >
                    <Text style={styles.veiculoIcon}>{v.icon}</Text>
                    <Text style={[
                      styles.veiculoNome,
                      veiculo === v.id && styles.veiculoNomeSelected,
                    ]}>
                      {v.nome}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>🚗</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Placa do veículo"
                  placeholderTextColor={colors.gray[400]}
                  value={placa}
                  onChangeText={setPlaca}
                  autoCapitalize="characters"
                  maxLength={8}
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>🏭</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Marca (ex: Honda)"
                  placeholderTextColor={colors.gray[400]}
                  value={marca}
                  onChangeText={setMarca}
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputIcon}>📝</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Modelo (ex: CG 160)"
                  placeholderTextColor={colors.gray[400]}
                  value={modelo}
                  onChangeText={setModelo}
                />
              </View>

              <TouchableOpacity
                style={[styles.button, loading && styles.buttonDisabled]}
                onPress={handleCadastro}
                disabled={loading}
              >
                {loading ? (
                  <ActivityIndicator color={colors.white} />
                ) : (
                  <Text style={styles.buttonText}>Finalizar Cadastro</Text>
                )}
              </TouchableOpacity>
            </>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.entregador.primary,
  },
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing.xxl,
  },
  header: {
    paddingTop: spacing.xl,
    paddingBottom: spacing.lg,
  },
  backButton: {
    color: colors.white,
    fontSize: fonts.sizes.md,
    marginBottom: spacing.lg,
  },
  title: {
    fontSize: fonts.sizes.xxl,
    fontWeight: 'bold',
    color: colors.white,
  },
  subtitle: {
    fontSize: fonts.sizes.md,
    color: 'rgba(255, 255, 255, 0.8)',
    marginTop: spacing.xs,
  },
  progressBar: {
    height: 4,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    borderRadius: 2,
    marginTop: spacing.md,
  },
  progressFill: {
    height: '100%',
    backgroundColor: colors.white,
    borderRadius: 2,
  },
  form: {
    backgroundColor: colors.white,
    borderRadius: borderRadius.xl,
    padding: spacing.xl,
    ...shadows.lg,
  },
  formTitle: {
    fontSize: fonts.sizes.lg,
    fontWeight: 'bold',
    color: colors.gray[900],
    marginBottom: spacing.lg,
  },
  label: {
    fontSize: fonts.sizes.sm,
    fontWeight: '600',
    color: colors.gray[700],
    marginBottom: spacing.sm,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.gray[100],
    borderRadius: borderRadius.lg,
    marginBottom: spacing.md,
    paddingHorizontal: spacing.md,
  },
  inputIcon: {
    fontSize: 20,
    marginRight: spacing.sm,
  },
  input: {
    flex: 1,
    paddingVertical: spacing.md,
    fontSize: fonts.sizes.md,
    color: colors.gray[900],
  },
  veiculosGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: spacing.md,
    marginHorizontal: -spacing.xs,
  },
  veiculoCard: {
    width: '48%',
    backgroundColor: colors.gray[100],
    borderRadius: borderRadius.lg,
    padding: spacing.md,
    margin: '1%',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'transparent',
  },
  veiculoCardSelected: {
    borderColor: colors.entregador.primary,
    backgroundColor: '#e3f2fd',
  },
  veiculoIcon: {
    fontSize: 32,
    marginBottom: spacing.xs,
  },
  veiculoNome: {
    fontSize: fonts.sizes.sm,
    fontWeight: '600',
    color: colors.gray[700],
  },
  veiculoNomeSelected: {
    color: colors.entregador.primary,
  },
  button: {
    backgroundColor: colors.entregador.primary,
    borderRadius: borderRadius.lg,
    paddingVertical: spacing.md,
    alignItems: 'center',
    marginTop: spacing.md,
  },
  buttonDisabled: {
    opacity: 0.7,
  },
  buttonText: {
    color: colors.white,
    fontSize: fonts.sizes.lg,
    fontWeight: 'bold',
  },
});
