import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  ActivityIndicator,
  Modal,
  FlatList,
} 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 { executeQuery } from "../../services/database";
import { OfflineDelivery } from "../../services/offlineSyncService";

interface CheckoutScreenProps {
  navigation: any;
}

const CheckoutScreen: React.FC<CheckoutScreenProps> = ({ navigation }) => {
  const {
    syncStats,
    syncSpecificDeliveries,
    syncAllPendingDeliveries,
    isLoading,
    error,
    refreshSyncStats,
    checkConnectivity,
  } = useOfflineMode();

  const [selectedDeliveries, setSelectedDeliveries] = useState<string[]>([]);
  const [pendingDeliveries, setPendingDeliveries] = useState<OfflineDelivery[]>(
    []
  );
  const [showDeliveryList, setShowDeliveryList] = useState(false);
  const [syncResult, setSyncResult] = useState<any>(null);
  const [isOnline, setIsOnline] = useState(true);

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

  useEffect(() => {
    if (syncStats) {
      loadPendingDeliveries();
    }
  }, [syncStats]);

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

  const loadPendingDeliveries = async () => {
    try {
      const result = await executeQuery(
        "SELECT * FROM deliveries WHERE syncTimestamp IS NULL OR syncTimestamp < lastModified ORDER BY lastModified DESC"
      );
      setPendingDeliveries(result.rows._array);
    } catch (error) {
      console.error("Erro ao carregar entregas pendentes:", error);
    }
  };

  const handleSelectDelivery = (deliveryId: string) => {
    setSelectedDeliveries((prev) => {
      if (prev.includes(deliveryId)) {
        return prev.filter((id) => id !== deliveryId);
      } else {
        return [...prev, deliveryId];
      }
    });
  };

  const handleSelectAll = () => {
    if (selectedDeliveries.length === pendingDeliveries.length) {
      setSelectedDeliveries([]);
    } else {
      setSelectedDeliveries(pendingDeliveries.map((d) => d.id));
    }
  };

  const handleSyncSelected = async () => {
    if (selectedDeliveries.length === 0) {
      Alert.alert(
        "Aviso",
        "Selecione pelo menos uma entrega para sincronizar."
      );
      return;
    }

    if (!isOnline) {
      Alert.alert(
        "Sem Conexão",
        "É necessário estar conectado à internet para sincronizar.",
        [{ text: "OK" }]
      );
      return;
    }

    Alert.alert(
      "Confirmar Sincronização",
      `Deseja sincronizar ${selectedDeliveries.length} entrega(s) selecionada(s)?`,
      [
        { text: "Cancelar", style: "cancel" },
        {
          text: "Sincronizar",
          onPress: async () => {
            try {
              const result = await syncSpecificDeliveries(selectedDeliveries);
              setSyncResult(result);
              setSelectedDeliveries([]);

              if (result.success) {
                Alert.alert(
                  "Sucesso",
                  `${result.syncedRecords} entrega(s) sincronizada(s) com sucesso!`,
                  [{ text: "OK" }]
                );
              } else {
                Alert.alert(
                  "Aviso",
                  `${result.syncedRecords} entrega(s) sincronizada(s), ${result.failedRecords} falharam.`,
                  [{ text: "OK" }]
                );
              }
            } catch (error) {
              Alert.alert("Erro", "Falha na sincronização. Tente novamente.");
            }
          },
        },
      ]
    );
  };

  const handleSyncAll = async () => {
    if (pendingDeliveries.length === 0) {
      Alert.alert("Aviso", "Não há entregas pendentes para sincronizar.");
      return;
    }

    if (!isOnline) {
      Alert.alert(
        "Sem Conexão",
        "É necessário estar conectado à internet para sincronizar.",
        [{ text: "OK" }]
      );
      return;
    }

    Alert.alert(
      "Confirmar Sincronização",
      `Deseja sincronizar todas as ${pendingDeliveries.length} entregas pendentes?`,
      [
        { text: "Cancelar", style: "cancel" },
        {
          text: "Sincronizar Todas",
          onPress: async () => {
            try {
              const result = await syncAllPendingDeliveries();
              setSyncResult(result);

              if (result.success) {
                Alert.alert(
                  "Sucesso",
                  `${result.syncedRecords} entrega(s) sincronizada(s) com sucesso!`,
                  [{ text: "OK" }]
                );
              } else {
                Alert.alert(
                  "Aviso",
                  `${result.syncedRecords} entrega(s) sincronizada(s), ${result.failedRecords} falharam.`,
                  [{ text: "OK" }]
                );
              }
            } catch (error) {
              Alert.alert("Erro", "Falha na sincronização. Tente novamente.");
            }
          },
        },
      ]
    );
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleString("pt-BR");
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "completed":
        return COLORS.success;
      case "absent":
        return COLORS.warning;
      case "refused":
        return COLORS.danger;
      default:
        return COLORS.text;
    }
  };

  const renderDeliveryItem = ({ item }: { item: OfflineDelivery }) => {
    const isSelected = selectedDeliveries.includes(item.id);

    return (
      <TouchableOpacity
        style={[styles.deliveryItem, isSelected && styles.deliveryItemSelected]}
        onPress={() => handleSelectDelivery(item.id)}
      >
        <View style={styles.deliveryItemContent}>
          <View style={styles.deliveryHeader}>
            <Text style={styles.deliveryId}>#{item.outId}</Text>
            <View
              style={[
                styles.statusBadge,
                { backgroundColor: getStatusColor(item.status) },
              ]}
            >
              <Text style={styles.statusText}>{item.status.toUpperCase()}</Text>
            </View>
          </View>

          <Text style={styles.customerName}>{item.customerName}</Text>
          <Text style={styles.customerAddress}>
            {item.street}, {item.streetNumber} - {item.neighborhood}
          </Text>
          <Text style={styles.customerCity}>
            {item.city} - {item.state}
          </Text>

          <Text style={styles.lastModified}>
            Modificado: {formatDate(item.lastModified)}
          </Text>
        </View>

        <View style={styles.selectionIndicator}>
          <Ionicons
            name={isSelected ? "checkmark-circle" : "ellipse-outline"}
            size={24}
            color={isSelected ? COLORS.primary : COLORS.textLight}
          />
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      
        <LinearGradient
          colors={[COLORS.primary, "#3B82F6"]}
          style={styles.header}
        >
          <View style={styles.headerContent}>
            <TouchableOpacity
              style={styles.backButton}
              onPress={() => navigation.goBack()}
            >
              <Ionicons name="arrow-back" size={24} color="white" />
            </TouchableOpacity>
            <Text style={styles.title}>Sincronização</Text>
            <TouchableOpacity
              style={styles.refreshButton}
              onPress={refreshSyncStats}
            >
              <Ionicons name="refresh" size={24} color="white" />
            </TouchableOpacity>
          </View>
        </LinearGradient>

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

          {/* Estatísticas */}
          {syncStats && (
            <View style={styles.statsContainer}>
              <Text style={styles.statsTitle}>
                Estatísticas de Sincronização
              </Text>

              <View style={styles.statsRow}>
                <View style={styles.statItem}>
                  <Text style={styles.statNumber}>
                    {syncStats.totalDeliveries}
                  </Text>
                  <Text style={styles.statLabel}>Total</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={styles.statNumber}>
                    {syncStats.syncedDeliveries}
                  </Text>
                  <Text style={styles.statLabel}>Sincronizadas</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statNumber, { color: COLORS.warning }]}>
                    {syncStats.pendingDeliveries}
                  </Text>
                  <Text style={styles.statLabel}>Pendentes</Text>
                </View>
              </View>

              {syncStats.lastSyncTime && (
                <Text style={styles.lastSyncText}>
                  Última sincronização: {formatDate(syncStats.lastSyncTime)}
                </Text>
              )}
            </View>
          )}

          {/* Resultado da sincronização */}
          {syncResult && (
            <View style={styles.resultContainer}>
              <Text style={styles.resultTitle}>Resultado da Sincronização</Text>
              <Text style={styles.resultText}>
                Sincronizadas: {syncResult.syncedRecords}/
                {syncResult.totalRecords}
              </Text>
              <Text style={styles.resultText}>
                Duração: {(syncResult.duration / 1000).toFixed(1)}s
              </Text>
              {syncResult.errors.length > 0 && (
                <Text style={styles.errorText}>
                  Erros: {syncResult.errors.length}
                </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ões de ação */}
          <View style={styles.actionButtons}>
            <TouchableOpacity
              style={[
                styles.syncAllButton,
                (!isOnline || pendingDeliveries.length === 0) &&
                  styles.buttonDisabled,
              ]}
              onPress={handleSyncAll}
              disabled={
                !isOnline || pendingDeliveries.length === 0 || isLoading
              }
            >
              <Ionicons name="cloud-upload" size={24} color="white" />
              <Text style={styles.syncAllButtonText}>
                Sincronizar Todas ({pendingDeliveries.length})
              </Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[
                styles.selectButton,
                pendingDeliveries.length === 0 && styles.buttonDisabled,
              ]}
              onPress={() => setShowDeliveryList(true)}
              disabled={pendingDeliveries.length === 0}
            >
              <Ionicons name="list" size={24} color={COLORS.primary} />
              <Text style={styles.selectButtonText}>
                Selecionar Entregas ({selectedDeliveries.length})
              </Text>
            </TouchableOpacity>

            {selectedDeliveries.length > 0 && (
              <TouchableOpacity
                style={[
                  styles.syncSelectedButton,
                  !isOnline && styles.buttonDisabled,
                ]}
                onPress={handleSyncSelected}
                disabled={!isOnline || isLoading}
              >
                <Ionicons name="cloud-upload" size={24} color="white" />
                <Text style={styles.syncSelectedButtonText}>
                  Sincronizar Selecionadas ({selectedDeliveries.length})
                </Text>
              </TouchableOpacity>
            )}
          </View>

          {/* Loading */}
          {isLoading && (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color={COLORS.primary} />
              <Text style={styles.loadingText}>Sincronizando...</Text>
            </View>
          )}
        </ScrollView>
      </View>

      {/* Modal de lista de entregas */}
      <Modal
        visible={showDeliveryList}
        animationType="slide"
        presentationStyle="pageSheet"
      >
        <SafeAreaView style={styles.modalContainer}>
          <View style={styles.modalHeader}>
            <TouchableOpacity
              style={styles.modalCloseButton}
              onPress={() => setShowDeliveryList(false)}
            >
              <Ionicons name="close" size={24} color={COLORS.text} />
            </TouchableOpacity>
            <Text style={styles.modalTitle}>
              Selecionar Entregas ({pendingDeliveries.length})
            </Text>
            <TouchableOpacity
              style={styles.selectAllButton}
              onPress={handleSelectAll}
            >
              <Text style={styles.selectAllButtonText}>
                {selectedDeliveries.length === pendingDeliveries.length
                  ? "Desmarcar"
                  : "Marcar"}{" "}
                Todas
              </Text>
            </TouchableOpacity>
          </View>

          <FlatList
            data={pendingDeliveries}
            renderItem={renderDeliveryItem}
            keyExtractor={(item) => item.id}
            style={styles.deliveryList}
            showsVerticalScrollIndicator={false}
          />
        </SafeAreaView>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.primary,
    // backgroundColor: COLORS.background,
  },
  viewContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
    marginBottom: -50,
  },
  header: {
    paddingVertical: 20,
    paddingHorizontal: 20,
  },
  headerContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  backButton: {
    padding: 8,
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
    color: "white",
  },
  refreshButton: {
    padding: 8,
  },
  content: {
    flex: 1,
    padding: 20,
  },
  connectionStatus: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 20,
    padding: 12,
    backgroundColor: COLORS.secondary,
    borderRadius: 12,
  },
  connectionText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
  statsContainer: {
    backgroundColor: COLORS.secondary,
    padding: 20,
    borderRadius: 12,
    marginBottom: 20,
  },
  statsTitle: {
    fontSize: 18,
    fontWeight: "bold",
    color: COLORS.text,
    marginBottom: 16,
    textAlign: "center",
  },
  statsRow: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginBottom: 12,
  },
  statItem: {
    alignItems: "center",
  },
  statNumber: {
    fontSize: 24,
    fontWeight: "bold",
    color: COLORS.primary,
  },
  statLabel: {
    fontSize: 12,
    color: COLORS.textLight,
    marginTop: 4,
  },
  lastSyncText: {
    fontSize: 12,
    color: COLORS.textLight,
    textAlign: "center",
  },
  resultContainer: {
    backgroundColor: "#F0F9FF",
    padding: 16,
    borderRadius: 12,
    marginBottom: 20,
  },
  resultTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.primary,
    marginBottom: 8,
  },
  resultText: {
    fontSize: 14,
    color: COLORS.text,
    marginBottom: 4,
  },
  errorContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#FEF2F2",
    padding: 16,
    borderRadius: 12,
    marginBottom: 20,
  },
  errorText: {
    fontSize: 14,
    color: COLORS.danger,
    marginLeft: 8,
    flex: 1,
  },
  actionButtons: {
    marginBottom: 20,
  },
  syncAllButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.success,
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: 12,
    marginBottom: 12,
    ...SHADOWS.medium,
  },
  syncAllButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: "white",
    marginLeft: 8,
  },
  selectButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "white",
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: 12,
    marginBottom: 12,
    borderWidth: 2,
    borderColor: COLORS.primary,
    ...SHADOWS.medium,
  },
  selectButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: COLORS.primary,
    marginLeft: 8,
  },
  syncSelectedButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: COLORS.primary,
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: 12,
    marginBottom: 12,
    ...SHADOWS.medium,
  },
  syncSelectedButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: "white",
    marginLeft: 8,
  },
  buttonDisabled: {
    opacity: 0.5,
  },
  loadingContainer: {
    alignItems: "center",
    padding: 20,
  },
  loadingText: {
    fontSize: 16,
    color: COLORS.text,
    marginTop: 12,
  },
  modalContainer: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  modalHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  modalCloseButton: {
    padding: 8,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "bold",
    color: COLORS.text,
    flex: 1,
    textAlign: "center",
  },
  selectAllButton: {
    padding: 8,
  },
  selectAllButtonText: {
    fontSize: 14,
    fontWeight: "600",
    color: COLORS.primary,
  },
  deliveryList: {
    flex: 1,
    padding: 20,
  },
  deliveryItem: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "white",
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
    ...SHADOWS.small,
  },
  deliveryItemSelected: {
    borderWidth: 2,
    borderColor: COLORS.primary,
  },
  deliveryItemContent: {
    flex: 1,
  },
  deliveryHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 8,
  },
  deliveryId: {
    fontSize: 16,
    fontWeight: "bold",
    color: COLORS.text,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  statusText: {
    fontSize: 10,
    fontWeight: "bold",
    color: "white",
  },
  customerName: {
    fontSize: 16,
    fontWeight: "600",
    color: COLORS.text,
    marginBottom: 4,
  },
  customerAddress: {
    fontSize: 14,
    color: COLORS.textLight,
    marginBottom: 2,
  },
  customerCity: {
    fontSize: 14,
    color: COLORS.textLight,
    marginBottom: 8,
  },
  lastModified: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  selectionIndicator: {
    marginLeft: 12,
  },
});

export default CheckoutScreen;
