"use client"
import { View, Text, StyleSheet, TouchableOpacity, Alert, ScrollView, ActivityIndicator } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { COLORS, SIZES, SHADOWS } from "../../constants/theme"
import { useAuth } from "../../contexts/AuthContext"
import { useSync } from "../../contexts/SyncContext"
import { storageInfo } from "../../services/database"
import Icon from "../../../components/Icon"
import { useState, useEffect } from "react"
import { api } from "../../services/api"

interface DriverStats {
  totalDeliveries: number
  completedDeliveries: number
  pendingDeliveries: number
  inProgressDeliveries: number
  failedDeliveries: number
  totalDistance: number
  averageDeliveryTime: number
}

interface ProfileScreenProps {
  navigation: any;
}

const ProfileScreen = ({ navigation }: ProfileScreenProps) => {
  const { user, signOut } = useAuth()
  const { lastSyncTime, syncNow, isOnline } = useSync()
  const [driverStats, setDriverStats] = useState<DriverStats | null>(null)
  const [loadingStats, setLoadingStats] = useState(false)
  const [lastLoginTime, setLastLoginTime] = useState<string | null>(null)

  const getUserInitials = () => {
    if (!user?.name) return "M"
    const names = user.name.trim().split(" ").filter(name => name.length > 0)
    if (names.length >= 2) {
      return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
    }
    return names[0][0].toUpperCase()
  }

  // Carregar estatísticas do motorista
  const loadDriverStats = async () => {
    if (!isOnline) return
    
    setLoadingStats(true)
    try {
      const deliveries = await api.getDeliveries()
      
      const stats: DriverStats = {
        totalDeliveries: deliveries.length,
        completedDeliveries: deliveries.filter(d => d.status === 'delivered').length,
        pendingDeliveries: deliveries.filter(d => d.status === 'pending').length,
        inProgressDeliveries: deliveries.filter(d => d.status === 'in_progress').length,
        failedDeliveries: deliveries.filter(d => d.status === 'failed').length,
        totalDistance: 0, // Será calculado se necessário
        averageDeliveryTime: 0 // Será calculado se necessário
      }
      
      setDriverStats(stats)
    } catch (error) {
      console.error('Erro ao carregar estatísticas:', error)
    } finally {
      setLoadingStats(false)
    }
  }

  // Carregar dados quando a tela montar
  useEffect(() => {
    loadDriverStats()
    
    // Definir horário de login (simulado - em produção viria do backend)
    const now = new Date()
    setLastLoginTime(now.toLocaleString('pt-BR'))
  }, [isOnline])

  const handleSignOut = () => {
    Alert.alert(
      "Sair",
      "Tem certeza que deseja sair?",
      [
        {
          text: "Cancelar",
          style: "cancel",
        },
        {
          text: "Sair",
          onPress: async () => {
            console.log("=== DEBUG: LOGOUT SOLICITADO PELO USUÁRIO ===");
            try {
              await signOut();
              console.log("✅ Logout executado com sucesso");
            } catch (error) {
              console.error("❌ Erro no logout:", error);
              Alert.alert("Erro", "Erro ao fazer logout. Tente novamente.");
            }
          },
        },
      ],
      { cancelable: true },
    )
  }

  // Função de teste para logout direto (sem confirmação)
  const handleTestLogout = async () => {
    console.log("=== DEBUG: TESTE DE LOGOUT DIRETO ===");
    try {
      await signOut();
      console.log("✅ Teste de logout executado com sucesso");
    } catch (error) {
      console.error("❌ Erro no teste de logout:", error);
      Alert.alert("Erro", "Erro no teste de logout: " + error);
    }
  }

  const handleSync = async () => {
    if (!isOnline) {
      Alert.alert("Erro", "Você está offline. Conecte-se à internet para sincronizar.")
      return
    }

    // Navegar para a tela de sincronização
    navigation.navigate("DeliveriesStack", { screen: "Checkout" })
  }

  const formatDate = (date: any) => {
    if (!date) return "Nunca"
    return new Date(date).toLocaleString("pt-BR")
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'delivered': return COLORS.success
      case 'in_progress': return COLORS.primary
      case 'pending': return COLORS.warning
      case 'failed': return COLORS.danger
      default: return COLORS.textLight
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'delivered': return 'Entregues'
      case 'in_progress': return 'Em Andamento'
      case 'pending': return 'Pendentes'
      case 'failed': return 'Falhadas'
      default: return status
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView showsVerticalScrollIndicator={false}>
        {/* Header com dados do motorista */}
        <View style={styles.header}>
          <View style={styles.avatarContainer}>
            <Text style={styles.avatarText}>
              {getUserInitials()}
            </Text>
          </View>
          <Text style={styles.userName}>{user?.name || "Motorista"}</Text>
          <Text style={styles.userEmail}>{user?.email || "motorista@empresa.com"}</Text>
          <Text style={styles.userId}>ID: {user?.id || "N/A"}</Text>
          {user?.sellerId && (
            <Text style={styles.sellerId}>Vendedor ID: {user.sellerId}</Text>
          )}
        </View>

        {/* Estatísticas do motorista */}
        <View style={styles.statsCard}>
          <Text style={styles.cardTitle}>📊 Estatísticas do Dia</Text>
          
          {loadingStats ? (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="small" color={COLORS.primary} />
              <Text style={styles.loadingText}>Carregando estatísticas...</Text>
            </View>
          ) : driverStats ? (
            <View style={styles.statsGrid}>
              <View style={styles.statItem}>
                <Text style={styles.statNumber}>{driverStats.totalDeliveries}</Text>
                <Text style={styles.statLabel}>Total</Text>
              </View>
              <View style={styles.statItem}>
                <Text style={[styles.statNumber, { color: COLORS.success }]}>
                  {driverStats.completedDeliveries}
                </Text>
                <Text style={styles.statLabel}>Entregues</Text>
              </View>
              <View style={styles.statItem}>
                <Text style={[styles.statNumber, { color: COLORS.primary }]}>
                  {driverStats.inProgressDeliveries}
                </Text>
                <Text style={styles.statLabel}>Em Andamento</Text>
              </View>
              <View style={styles.statItem}>
                <Text style={[styles.statNumber, { color: COLORS.warning }]}>
                  {driverStats.pendingDeliveries}
                </Text>
                <Text style={styles.statLabel}>Pendentes</Text>
              </View>
            </View>
          ) : (
            <Text style={styles.noDataText}>Nenhuma estatística disponível</Text>
          )}
        </View>

        {/* Informações do sistema */}
        <View style={styles.infoCard}>
          <Text style={styles.infoTitle}>⚙️ Informações do Sistema</Text>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Armazenamento:</Text>
            <Text style={styles.infoValue}>SQLite</Text>
            {/* <Text style={styles.infoValue}>{storageInfo.type}</Text> */}
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Status:</Text>
            <View style={styles.statusContainer}>
              <View style={[styles.statusIndicator, { backgroundColor: isOnline ? COLORS.success : COLORS.warning }]} />
              <Text style={styles.statusText}>{isOnline ? "Online" : "Offline"}</Text>
            </View>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Última sincronização:</Text>
            <Text style={styles.infoValue}>{formatDate(lastSyncTime)}</Text>
          </View>

          {lastLoginTime && (
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>Login realizado:</Text>
              <Text style={styles.infoValue}>{lastLoginTime}</Text>
            </View>
          )}

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Loja ID:</Text>
            <Text style={styles.infoValue}>{user?.storeId || "N/A"}</Text>
          </View>
        </View>

        {/* Botões de ação */}
        <TouchableOpacity
          style={[styles.button, { backgroundColor: COLORS.primary }]}
          onPress={handleSync}
          disabled={!isOnline}
        >
          <Icon type="material" name="sync" size={20} color="#fff" style={{ marginRight: 8 }} />
          <Text style={styles.buttonText}>Sincronizar entregas realizadas</Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={[styles.button, { backgroundColor: COLORS.danger }]} 
          onPress={handleSignOut}
        >
          <Icon type="material" name="logout" size={20} color="#fff" style={{ marginRight: 8 }} />
          <Text style={styles.buttonText}>Sair</Text>
        </TouchableOpacity>

        {/* Botão de teste de logout 
        <TouchableOpacity 
          style={[styles.button, { backgroundColor: COLORS.warning }]} 
          onPress={handleTestLogout}
        >
          <Icon type="material" name="bug-report" size={20} color="#fff" style={{ marginRight: 8 }} />
          <Text style={styles.buttonText}>Testar Logout</Text>
        </TouchableOpacity>*/}
      </ScrollView>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    alignItems: "center",
    marginBottom: 24,
    padding: 16,
  },
  avatarContainer: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: COLORS.primary,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 16,
    ...SHADOWS.medium,
  },
  avatarText: {
    fontSize: 32,
    fontWeight: "bold",
    color: "#fff",
  },
  userName: {
    fontSize: SIZES.large,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 4,
    textAlign: "center",
  },
  userEmail: {
    fontSize: SIZES.font,
    color: COLORS.textLight,
    marginBottom: 4,
    textAlign: "center",
  },
  userId: {
    fontSize: SIZES.small,
    color: COLORS.textLight,
    marginBottom: 2,
  },
  sellerId: {
    fontSize: SIZES.small,
    color: COLORS.textLight,
  },
  statsCard: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    padding: 16,
    marginHorizontal: 16,
    marginBottom: 16,
    ...SHADOWS.medium,
  },
  cardTitle: {
    fontSize: SIZES.medium,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 16,
  },
  loadingContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    padding: 20,
  },
  loadingText: {
    marginLeft: 8,
    color: COLORS.textLight,
    fontSize: SIZES.font,
  },
  statsGrid: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  statItem: {
    alignItems: "center",
    flex: 1,
  },
  statNumber: {
    fontSize: 24,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 4,
  },
  statLabel: {
    fontSize: SIZES.small,
    color: COLORS.textLight,
    textAlign: "center",
  },
  noDataText: {
    textAlign: "center",
    color: COLORS.textLight,
    fontSize: SIZES.font,
    fontStyle: "italic",
  },
  infoCard: {
    backgroundColor: COLORS.card,
    borderRadius: 12,
    padding: 16,
    marginHorizontal: 16,
    marginBottom: 24,
    ...SHADOWS.medium,
  },
  infoTitle: {
    fontSize: SIZES.medium,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 16,
  },
  infoRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 12,
  },
  infoLabel: {
    fontSize: SIZES.font,
    color: COLORS.textLight,
  },
  infoValue: {
    fontSize: SIZES.font,
    color: COLORS.text,
    fontWeight: "500",
  },
  statusContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  statusIndicator: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: 6,
  },
  statusText: {
    fontSize: SIZES.font,
    color: COLORS.text,
  },
  button: {
    flexDirection: "row",
    borderRadius: 12,
    padding: 16,
    alignItems: "center",
    justifyContent: "center",
    marginHorizontal: 16,
    marginBottom: 16,
    ...SHADOWS.medium,
  },
  buttonText: {
    color: "#fff",
    fontSize: SIZES.medium,
    fontWeight: "bold",
  },
})

export default ProfileScreen

