import React, { useState, useEffect } from "react";
import {
  View,
  ScrollView,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  Dimensions,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { COLORS, SHADOWS } from "../../constants/theme";
import { useOfflineMode } from "../../contexts/OfflineModeContext";
import { useAuth } from "../../contexts/AuthContext";
// import { logout } from '../../services/api';

const { width } = Dimensions.get("window");

const InitialDataLoadScreen: React.FC = () => {
  const { user, signOut } = useAuth();
  const { loadInitialData, isLoading: contextIsLoading, error, checkConnectivity } =
    useOfflineMode();

  const [progress, setProgress] = useState(0);
  const [statusText, setStatusText] = useState("Preparando...");
  const [isOnline, setIsOnline] = useState(true);
  const [isLoadingLocal, setIsLoadingLocal] = useState(false);
  
  // Usar estado local para controlar o loading, não o do contexto
  const isLoading = isLoadingLocal || contextIsLoading;

  useEffect(() => {
    checkConnectivityStatus();
  }, []);

  const checkConnectivityStatus = async () => {
    const online = await checkConnectivity();
    setIsOnline(online);

    if (!online) {
      setStatusText("Sem conexão com a internet");
    } else {
      setStatusText("Pronto para carregar dados");
    }
  };

  const handleLoadData = async () => {
    if (!isOnline) {
      Alert.alert(
        "Sem Conexão",
        "É necessário estar conectado à internet para carregar os dados iniciais.",
        [{ text: "OK" }]
      );
      return;
    }

    try {
      setIsLoadingLocal(true);
      setProgress(0);
      setStatusText("Verificando conexão...");

      // Simular progresso
      const progressInterval = setInterval(() => {
        setProgress((prev) => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 200);

      setStatusText("Carregando entregas...");
      await new Promise((resolve) => setTimeout(resolve, 500));

      setStatusText("Carregando dados de clientes...");
      await new Promise((resolve) => setTimeout(resolve, 500));

      setStatusText("Salvando dados localmente...");
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Carregar dados reais
      await loadInitialData();

      clearInterval(progressInterval);
      setProgress(100);
      setStatusText("Dados carregados com sucesso!");

      // Navegar para a tela principal após um breve delay
      setTimeout(() => {
        // A navegação será feita pelo contexto pai
      }, 1500);
    } catch (error) {
      setStatusText("Erro ao carregar dados");
      setProgress(0);
      Alert.alert(
        "Erro",
        (error as Error)?.message ||
          "Falha ao carregar dados iniciais. Tente novamente.",
        [{ text: "OK" }]
      );
    } finally {
      setIsLoadingLocal(false);
    }
  };

  const getStatusColor = () => {
    if (error) return COLORS.danger;
    if (progress === 100) return COLORS.success;
    if (isLoading) return COLORS.primary;
    return COLORS.text;
  };

  const handleLogout = async () => {
    Alert.alert("Confirmar Logout", "Tem certeza que deseja sair?", [
      {
        text: "Cancelar",
        style: "cancel",
      },
      {
        text: "Sair",
        style: "destructive",
        onPress: async () => {
          try {
            // Fazer logout local apenas
            await signOut();
          } catch (error) {
            // Mesmo com erro, fazer logout local
            await signOut();
          }
        },
      },
    ]);
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.viewContainer}>
        <LinearGradient
          colors={[COLORS.primary, "#3B82F6"]}
          style={styles.header}
        >
          {/* Botão de logout no canto superior direito */}
          <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
            <Ionicons name="log-out-outline" size={24} color="white" />
          </TouchableOpacity>

          <View style={styles.headerContent}>
            <Ionicons name="cloud-download" size={64} color="white" />
            <Text style={styles.title}>Carregamento de Dados</Text>
            <Text style={styles.subtitle}>
              Baixando entregas e dados de clientes para funcionamento offline
            </Text>
          </View>
        </LinearGradient>

        <ScrollView showsVerticalScrollIndicator={false}>
          <View style={styles.content}>
            {/* Informações do usuário */}
            <View style={styles.userInfo}>
              <Ionicons name="person-circle" size={48} color={COLORS.primary} />
              <Text style={styles.userName}>{user?.name || "Usuário"}</Text>
              <Text style={styles.userEmail}>
                {user?.email || user?.username}
              </Text>
            </View>

            {/* Status da conexão */}
            <View style={styles.connectionStatus}>
              <Ionicons
                name={isOnline ? "wifi" : "cloud-offline"}
                size={24}
                color={isOnline ? COLORS.success : COLORS.danger}
              />
              <Text
                style={[
                  styles.connectionText,
                  { color: isOnline ? COLORS.success : COLORS.danger },
                ]}
              >
                {isOnline ? "Conectado" : "Desconectado"}
              </Text>
            </View>

            {/* Barra de progresso */}
            <View style={styles.progressContainer}>
              <View style={styles.progressBar}>
                <View
                  style={[styles.progressFill, { width: `${progress}%` }]}
                />
              </View>
              <Text style={styles.progressText}>
                {Math.round(progress)}% concluído
              </Text>
            </View>

            {/* Status atual */}
            <View style={styles.statusContainer}>
              <Text style={[styles.statusText, { color: getStatusColor() }]}>
                {statusText}
              </Text>
            </View>

            {/* Erro */}
            {error && (
              <View style={styles.errorContainer}>
                <Ionicons name="alert-circle" size={24} color={COLORS.danger} />
                <Text style={styles.errorText}>{error}</Text>
              </View>
            )}

            {/* Botão de ação */}
            <View style={styles.buttonContainer}>
              {!isLoadingLocal && progress < 100 ? (
                <TouchableOpacity
                  style={[
                    styles.loadButton,
                    (!isOnline || isLoadingLocal) && styles.loadButtonDisabled,
                  ]}
                  onPress={handleLoadData}
                  disabled={!isOnline || isLoadingLocal}
                >
                  <Ionicons name="cloud-download" size={24} color="white" />
                  <Text style={styles.loadButtonText}>
                    Iniciar carga de dados de entregas
                  </Text>
                </TouchableOpacity>
              ) : isLoadingLocal ? (
                <View style={styles.loadingContainer}>
                  <ActivityIndicator size="large" color={COLORS.primary} />
                  <Text style={styles.loadingText}>Carregando...</Text>
                </View>
              ) : progress === 100 ? (
                <View style={styles.successContainer}>
                  <Ionicons
                    name="checkmark-circle"
                    size={64}
                    color={COLORS.success}
                  />
                  <Text style={styles.successText}>
                    Dados carregados com sucesso!
                  </Text>
                  <Text style={styles.successSubtext}>
                    Entregas, clientes e notas fiscais prontos para uso offline
                  </Text>
                </View>
              ) : (
                <TouchableOpacity
                  style={[
                    styles.loadButton,
                    (!isOnline || isLoadingLocal) && styles.loadButtonDisabled,
                  ]}
                  onPress={handleLoadData}
                  disabled={!isOnline || isLoadingLocal}
                >
                  <Ionicons name="cloud-download" size={24} color="white" />
                  <Text style={styles.loadButtonText}>
                    Iniciar carga de dados de entregas
                  </Text>
                </TouchableOpacity>
              )}
            </View>

            {/* Informações sobre o processo */}
            <View style={styles.infoContainer}>
              <Text style={styles.infoTitle}>O que será carregado:</Text>
              <View style={styles.infoItem}>
                <Ionicons name="checkmark" size={16} color={COLORS.success} />
                <Text style={styles.infoText}>Lista de entregas</Text>
              </View>
              <View style={styles.infoItem}>
                <Ionicons name="checkmark" size={16} color={COLORS.success} />
                <Text style={styles.infoText}>
                  Dados de clientes e endereços
                </Text>
              </View>
              <View style={styles.infoItem}>
                <Ionicons name="checkmark" size={16} color={COLORS.success} />
                <Text style={styles.infoText}>Configurações do sistema</Text>
              </View>
              <View style={styles.infoItem}>
                <Ionicons name="checkmark" size={16} color={COLORS.success} />
                <Text style={styles.infoText}>Dados salvos localmente</Text>
              </View>
            </View>
          </View>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.primary,
    // backgroundColor: COLORS.background,
  },
  viewContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
    marginBottom: -50,
  },
  header: {
    paddingVertical: 40,
    paddingHorizontal: 20,
    alignItems: "center",
    position: "relative",
  },
  headerContent: {
    alignItems: "center",
  },
  title: {
    fontSize: 28,
    fontWeight: "bold",
    color: "white",
    marginTop: 16,
    marginBottom: 8,
    textAlign: "center",
  },
  subtitle: {
    fontSize: 16,
    color: "rgba(255, 255, 255, 0.8)",
    textAlign: "center",
    lineHeight: 22,
  },
  content: {
    flex: 1,
    padding: 20,
  },
  userInfo: {
    alignItems: "center",
    marginBottom: 30,
    padding: 20,
    backgroundColor: COLORS.secondary,
    borderRadius: 16,
  },
  userName: {
    fontSize: 20,
    fontWeight: "bold",
    color: COLORS.text,
    marginTop: 8,
  },
  userEmail: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 4,
  },
  connectionStatus: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 30,
    padding: 12,
    backgroundColor: COLORS.secondary,
    borderRadius: 12,
  },
  connectionText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
  progressContainer: {
    marginBottom: 30,
  },
  progressBar: {
    height: 12,
    backgroundColor: COLORS.border,
    borderRadius: 6,
    overflow: "hidden",
    marginBottom: 12,
  },
  progressFill: {
    height: "100%",
    backgroundColor: COLORS.primary,
    borderRadius: 6,
  },
  progressText: {
    fontSize: 16,
    fontWeight: "600",
    color: COLORS.text,
    textAlign: "center",
  },
  statusContainer: {
    alignItems: "center",
    marginBottom: 30,
  },
  statusText: {
    fontSize: 18,
    fontWeight: "600",
    textAlign: "center",
  },
  errorContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#FEF2F2",
    padding: 16,
    borderRadius: 12,
    marginBottom: 20,
  },
  errorText: {
    fontSize: 14,
    color: COLORS.danger,
    marginLeft: 8,
    flex: 1,
  },
  buttonContainer: {
    marginBottom: 30,
  },
  loadButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.primary,
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: 12,
    ...SHADOWS.medium,
  },
  loadButtonDisabled: {
    backgroundColor: COLORS.textLight,
  },
  loadButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: "white",
    marginLeft: 8,
  },
  loadingContainer: {
    alignItems: "center",
    padding: 20,
  },
  loadingText: {
    fontSize: 16,
    color: COLORS.text,
    marginTop: 12,
  },
  successContainer: {
    alignItems: "center",
    padding: 20,
  },
  successText: {
    fontSize: 20,
    fontWeight: "bold",
    color: COLORS.success,
    marginTop: 16,
    textAlign: "center",
  },
  successSubtext: {
    fontSize: 14,
    color: COLORS.textLight,
    marginTop: 8,
    textAlign: "center",
  },
  infoContainer: {
    backgroundColor: COLORS.secondary,
    padding: 20,
    borderRadius: 12,
  },
  infoTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 12,
  },
  infoItem: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 8,
  },
  infoText: {
    fontSize: 14,
    color: COLORS.textLight,
    marginLeft: 8,
  },
  logoutButton: {
    position: "absolute",
    top: 20,
    right: 20,
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    alignItems: "center",
    justifyContent: "center",
    zIndex: 1,
  },
});

export default InitialDataLoadScreen;
