"use client"

import { useState } from "react"
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Image,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  ActivityIndicator,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { useAuth } from "../../contexts/AuthContext"
import { COLORS, SHADOWS } from "../../constants/theme"
import { storageInfo } from "../../services/database"
import Icon from "../../../components/Icon"
import IconSvg from '../../assets/images/logo/icone.svg'
import { useNavigation } from '@react-navigation/native'

const LoginScreen = () => {
  // const [username, setUsername] = useState("PAULO.CL")
  // const [password, setPassword] = useState("123456")
  // const [username, setUsername] = useState("FRANCISCOMELO.C")
  // const [password, setPassword] = useState("123456*J")
  // const [username, setUsername] = useState("EDIVALDO")
  // const [password, setPassword] = useState("123456")
  // const [username, setUsername] = useState("JONAS.R")
  // const [password, setPassword] = useState("PADRAO")
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const { signIn } = useAuth()
  const navigation = useNavigation()

  const handleLogin = async () => {
    // console.log('=== 🚪 DEBUG: INICIANDO HANDLE LOGIN ===');
    // console.log('Username:', username);
    // console.log('Password:', password ? '***' : 'vazio');
    
    if (!username.trim()) {
      // console.log('❌ Username vazio');
      Alert.alert("Erro", "Por favor, insira seu nome de usuário")
      return
    }

    if (!password.trim()) {
      // console.log('❌ Password vazio');
      Alert.alert("Erro", "Por favor, insira sua senha")
      return
    }

    setIsLoading(true)
    try {
      // console.log('=== 🚪 DEBUG: CHAMANDO SIGNIN ===');
      const result = await signIn(username.toUpperCase(), password.toUpperCase())
      // console.log('📋 Resultado do signIn:', result);
      
      if (result.success) {
        // console.log('✅ Login bem-sucedido');
        if (result.needsRouting) {
          // console.log('🔄 Precisa de roteirização - Navegando para RoutingScreen');
          // console.log('🧭 Tentando navegar para Routing...');
          
          try {
            // Redirecionar para tela de roteirização
            // Usar reset para evitar voltar para login
            navigation.reset({
              index: 0,
              routes: [{ name: 'Routing' as never }],
            });
            // console.log('✅ Navegação para Routing executada com sucesso');
          } catch (navError) {
            // console.error('❌ Erro na navegação para Routing:', navError);
            // Fallback: tentar navegar para Main
            // console.log('🔄 Tentando fallback para Main...');
            navigation.reset({
              index: 0,
              routes: [{ name: 'Main' as never }],
            });
          }
        } else {
          // console.log('✅ Não precisa de roteirização - Usuário será redirecionado para Home');
        }
        // Se não precisar de roteirização, o usuário será redirecionado automaticamente para Home
      } else {
        // console.log('❌ Login falhou');
        Alert.alert(
          "Erro no Login",
          "Não foi possível fazer login. Verifique suas credenciais e tente novamente."
        )
      }
    } catch (error) {
      // console.error("❌ Erro ao fazer login:", error)
      let errorMessage = "Ocorreu um erro ao fazer login. Tente novamente."
      
      if (error instanceof Error) {
        if (error.message.includes("network")) {
          errorMessage = "Erro de conexão. Verifique sua internet e tente novamente."
        } else if (error.message.includes("401")) {
          errorMessage = "Nome de usuário ou senha incorretos."
        }
      }
      
      Alert.alert("Erro", errorMessage)
    } finally {
      setIsLoading(false)
      // console.log('=== 🚪 DEBUG: HANDLE LOGIN FINALIZADO ===');
    }
  }

  const handleSocialLogin = (provider: 'Google' | 'Apple') => {
    Alert.alert("Login Social", `Login com ${provider} será implementado em breve.`)
  }

  const handleSignUp = () => {
    Alert.alert("Cadastro", "Funcionalidade de cadastro será implementada em breve.")
  }

  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={{ flex: 1 }}>
        <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
          <View style={styles.logoContainer}>
            <IconSvg width={80} height={80} />
          </View>

          <View style={styles.headerContainer}>
            <Text style={styles.headerTitle}>Entregas</Text>
            <Text style={styles.headerSubtitle}>Bem-vindo de volta, sentimos sua falta!</Text>
          </View>

          <View style={styles.formContainer}>
            <Text style={styles.label}>Nome de Usuário</Text>
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.input}
                placeholder="Seu nome de usuário"
                value={username}
                onChangeText={setUsername}
                autoCapitalize="none"
                autoCorrect={false}
                placeholderTextColor="#333333"
              />
            </View>

            <Text style={styles.label}>Senha</Text>
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.input}
                placeholder="Sua senha"
                value={password}
                onChangeText={setPassword}
                secureTextEntry={!showPassword}
                placeholderTextColor="#333333"
              />
              <TouchableOpacity style={styles.passwordToggle} onPress={() => setShowPassword(!showPassword)}>
                <Icon
                  type="material"
                  name={showPassword ? "visibility" : "visibility-off"}
                  size={20}
                  color={COLORS.textLight}
                />
              </TouchableOpacity>
            </View>

            <TouchableOpacity style={styles.forgotPasswordContainer}>
              <Text style={styles.forgotPassword}>Esqueceu sua senha?</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.loginButton} onPress={handleLogin} disabled={isLoading}>
              {isLoading ? <ActivityIndicator color="#fff" /> : <Text style={styles.loginButtonText}>Entrar</Text>}
            </TouchableOpacity>

            <View style={styles.dividerContainer}>
              <View style={styles.divider} />
              <Text style={styles.dividerText}>Ou continue com</Text>
              <View style={styles.divider} />
            </View>

            <View style={styles.socialContainer}>
              <TouchableOpacity style={styles.socialButton} onPress={() => handleSocialLogin("Google")}>
                <Icon type="font-awesome" name="google" size={20} color="#DB4437" />
              </TouchableOpacity>

              <TouchableOpacity style={styles.socialButton} onPress={() => handleSocialLogin("Apple")}>
                <Icon type="font-awesome" name="apple" size={20} color="#000000" />
              </TouchableOpacity>
            </View>

            <View style={styles.signupContainer}>
              <Text style={styles.signupText}>Não tem uma conta? </Text>
              <TouchableOpacity onPress={handleSignUp}>
                <Text style={styles.signupLink}>Cadastre-se</Text>
              </TouchableOpacity>
            </View>
          </View>

          {/* Indicador do tipo de armazenamento - mantido para desenvolvimento 
          <View style={styles.storageInfoContainer}>
            <Text style={styles.storageInfoText}>Usando: {storageInfo.type}</Text>
          </View>*/}
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: "center",
    padding: 20,
  },
  logoContainer: {
    alignItems: "center",
    marginBottom: 20,
  },
  logo: {
    width: 80,
    height: 80,
    resizeMode: "contain",
  },
  headerContainer: {
    alignItems: "center",
    marginBottom: 30,
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 8,
  },
  headerSubtitle: {
    fontSize: 16,
    color: COLORS.textLight,
    textAlign: "center",
  },
  formContainer: {
    width: "100%",
    maxWidth: 400,
    alignSelf: "center",
  },
  label: {
    fontSize: 14,
    marginBottom: 8,
    color: COLORS.textLight,
  },
  inputContainer: {
    position: "relative",
    marginBottom: 20,
  },
  input: {
    backgroundColor: COLORS.secondary,
    borderRadius: 12,
    padding: 15,
    fontSize: 16,
    color: COLORS.text,
    width: "100%",
  },
  passwordToggle: {
    position: "absolute",
    right: 15,
    top: 15,
  },
  forgotPasswordContainer: {
    alignItems: "flex-end",
    marginBottom: 24,
  },
  forgotPassword: {
    color: COLORS.textLight,
    fontSize: 14,
  },
  loginButton: {
    backgroundColor: COLORS.primary,
    borderRadius: 12,
    padding: 16,
    alignItems: "center",
    marginBottom: 24,
  },
  loginButtonText: {
    color: "#FFFFFF",
    fontSize: 16,
    fontWeight: "bold",
  },
  dividerContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 24,
  },
  divider: {
    flex: 1,
    height: 1,
    backgroundColor: COLORS.border,
  },
  dividerText: {
    paddingHorizontal: 10,
    color: COLORS.textLight,
    fontSize: 14,
  },
  socialContainer: {
    flexDirection: "row",
    justifyContent: "center",
    marginBottom: 24,
  },
  socialButton: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: COLORS.secondary,
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: 10,
    ...SHADOWS.small,
  },
  signupContainer: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
  },
  signupText: {
    color: COLORS.textLight,
    fontSize: 14,
  },
  signupLink: {
    color: COLORS.primary,
    fontSize: 14,
    fontWeight: "bold",
  },
  storageInfoContainer: {
    marginTop: 20,
    padding: 5,
    backgroundColor: COLORS.secondary,
    borderRadius: 5,
    alignItems: "center",
  },
  storageInfoText: {
    fontSize: 12,
    color: COLORS.textLight,
  },
})

export default LoginScreen

