"use client"

import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  ActivityIndicator,
  FlatList,
  RefreshControl,
} from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import DateTimePicker from '@react-native-community/datetimepicker';
import { SafeAreaView } from 'react-native-safe-area-context';
import { COLORS, SIZES, SHADOWS } from '../../constants/theme';
import { api } from '../../services/api';
import { offlineSyncService } from '../../services/offlineSyncService';
import Icon from '../../../components/Icon';

const RescheduleDeliveryScreen = () => {
  const route = useRoute();
  const navigation = useNavigation();
  const { deliveryId } = route.params || {};
  
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [showTimePicker, setShowTimePicker] = useState(false);
  const [loading, setLoading] = useState(false);
  const [pendingDeliveries, setPendingDeliveries] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [showPendingList, setShowPendingList] = useState(true);

  // Carregar entregas pendentes
  const loadPendingDeliveries = async () => {
    try {
      const deliveries = await offlineSyncService.getPendingDeliveries();
      setPendingDeliveries(deliveries);
    } catch (error) {
      // Silently fail
    }
  };

  // Carregar dados na montagem do componente
  useEffect(() => {
    loadPendingDeliveries();
  }, []);

  // Função de refresh
  const onRefresh = async () => {
    setRefreshing(true);
    await loadPendingDeliveries();
    setRefreshing(false);
  };

  const handleDateChange = (event: any, date?: Date) => {
    setShowDatePicker(false);
    if (date) {
      setSelectedDate(date);
    }
  };

  const handleTimeChange = (event: any, time?: Date) => {
    setShowTimePicker(false);
    if (time) {
      const newDate = new Date(selectedDate);
      newDate.setHours(time.getHours());
      newDate.setMinutes(time.getMinutes());
      setSelectedDate(newDate);
    }
  };

  const handleReschedule = async () => {
    try {
      setLoading(true);
      
      // Aqui você implementaria a chamada à API para atualizar a data/hora da entrega
      // Por enquanto, vamos apenas simular um delay
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      Alert.alert(
        'Sucesso',
        'Entrega reagendada com sucesso!',
        [
          {
            text: 'OK',
            onPress: () => navigation.goBack(),
          },
        ]
      );
    } catch (error) {
      Alert.alert(
        'Erro',
        'Não foi possível reagendar a entrega. Tente novamente.'
      );
    } finally {
      setLoading(false);
    }
  };

  // Função para sincronizar entrega específica
  const syncDelivery = async (deliveryId: string) => {
    try {
      setLoading(true);
      
      await offlineSyncService.syncSpecificDeliveries([deliveryId]);
      
      Alert.alert(
        'Sucesso',
        'Entrega sincronizada com sucesso!',
        [
          {
            text: 'OK',
            onPress: () => loadPendingDeliveries(),
          },
        ]
      );
    } catch (error) {
      Alert.alert(
        'Erro',
        'Não foi possível sincronizar a entrega. Tente novamente.'
      );
    } finally {
      setLoading(false);
    }
  };

  // Função para sincronizar todas as entregas
  const syncAllDeliveries = async () => {
    try {
      setLoading(true);
      
      // Usar syncAllPendingDeliveries que já busca todas as pendentes
      const result = await offlineSyncService.syncAllPendingDeliveries();
      
      if (result.success) {
        Alert.alert(
          'Sucesso',
          `${result.syncedRecords} entrega(s) sincronizada(s) com sucesso!`,
          [
            {
              text: 'OK',
              onPress: () => loadPendingDeliveries(),
            },
          ]
        );
      } else {
        Alert.alert(
          'Aviso',
          `${result.syncedRecords} entrega(s) sincronizada(s), ${result.failedRecords} falharam.`,
          [
            {
              text: 'OK',
              onPress: () => loadPendingDeliveries(),
            },
          ]
        );
      }
    } catch (error: any) {
      Alert.alert(
        'Erro',
        error?.message || 'Não foi possível sincronizar as entregas. Tente novamente.'
      );
    } finally {
      setLoading(false);
    }
  };

  // Renderizar item da lista
  const renderDeliveryItem = ({ item }) => (
    <View style={styles.deliveryItem}>
      <View style={styles.deliveryHeader}>
        <Text style={styles.customerName}>{item.customerName}</Text>
        <View style={styles.statusBadge}>
          <Text style={styles.statusText}>{item.status}</Text>
        </View>
      </View>
      
      <Text style={styles.address}>
        {item.street}, {item.streetNumber} - {item.neighborhood}
      </Text>
      <Text style={styles.city}>{item.city} - {item.state}</Text>
      
      <View style={styles.deliveryInfo}>
        <View style={styles.infoRow}>
          <Icon type="material" name="photo-camera" size={16} color={COLORS.primary} />
          <Text style={styles.infoText}>
            {item.pendingPhotos} fotos pendentes
          </Text>
        </View>
        
        {item.hasSignature && (
          <View style={styles.infoRow}>
            <Icon type="material" name="edit" size={16} color={COLORS.primary} />
            <Text style={styles.infoText}>Assinatura capturada</Text>
          </View>
        )}
        
        <View style={styles.infoRow}>
          <Icon type="material" name="schedule" size={16} color={COLORS.primary} />
          <Text style={styles.infoText}>
            {new Date(item.lastModified).toLocaleString('pt-BR')}
          </Text>
        </View>
      </View>
      
      <TouchableOpacity
        style={styles.syncButton}
        onPress={() => syncDelivery(item.id)}
        disabled={loading}
      >
        <Icon type="material" name="sync" size={20} color="#fff" />
        <Text style={styles.syncButtonText}>Sincronizar</Text>
      </TouchableOpacity>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon type="material" name="arrow-back" size={24} color={COLORS.text} />
        </TouchableOpacity>
        <Text style={styles.title}>Entregas Pendentes</Text>
        <TouchableOpacity
          style={styles.refreshButton}
          onPress={onRefresh}
          disabled={refreshing}
        >
          <Icon type="material" name="refresh" size={24} color={COLORS.text} />
        </TouchableOpacity>
      </View>

      {pendingDeliveries.length > 0 ? (
        <>
          <View style={styles.summaryContainer}>
            <Text style={styles.summaryText}>
              {pendingDeliveries.length} entregas pendentes de envio
            </Text>
            <TouchableOpacity
              style={styles.syncAllButton}
              onPress={syncAllDeliveries}
              disabled={loading}
            >
              <Icon type="material" name="sync" size={20} color="#fff" />
              <Text style={styles.syncAllButtonText}>Sincronizar Todas</Text>
            </TouchableOpacity>
          </View>

          <FlatList
            data={pendingDeliveries}
            renderItem={renderDeliveryItem}
            keyExtractor={(item) => item.id}
            refreshControl={
              <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }
            contentContainerStyle={styles.listContainer}
          />
        </>
      ) : (
        <View style={styles.emptyContainer}>
          <Icon type="material" name="check-circle" size={64} color={COLORS.primary} />
          <Text style={styles.emptyTitle}>Nenhuma entrega pendente</Text>
          <Text style={styles.emptyText}>
            Todas as entregas foram sincronizadas com sucesso!
          </Text>
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    backgroundColor: COLORS.primary,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  backButton: {
    padding: 8,
  },
  refreshButton: {
    padding: 8,
  },
  title: {
    fontSize: SIZES.large,
    fontWeight: 'bold',
    color: '#fff',
    flex: 1,
    textAlign: 'center',
  },
  summaryContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    backgroundColor: COLORS.card,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  summaryText: {
    fontSize: SIZES.medium,
    fontWeight: 'bold',
    color: COLORS.text,
  },
  syncAllButton: {
    backgroundColor: COLORS.primary,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 6,
  },
  syncAllButtonText: {
    color: '#fff',
    fontSize: SIZES.font,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  listContainer: {
    padding: 16,
  },
  deliveryItem: {
    backgroundColor: COLORS.card,
    padding: 16,
    borderRadius: 8,
    marginBottom: 12,
    ...SHADOWS.small,
  },
  deliveryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  customerName: {
    fontSize: SIZES.medium,
    fontWeight: 'bold',
    color: COLORS.text,
    flex: 1,
  },
  statusBadge: {
    backgroundColor: COLORS.primary,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
  },
  statusText: {
    color: '#fff',
    fontSize: SIZES.font,
    fontWeight: 'bold',
  },
  address: {
    fontSize: SIZES.font,
    color: COLORS.textLight,
    marginBottom: 4,
  },
  city: {
    fontSize: SIZES.font,
    color: COLORS.textLight,
    marginBottom: 12,
  },
  deliveryInfo: {
    marginBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  infoText: {
    marginLeft: 8,
    fontSize: SIZES.font,
    color: COLORS.textLight,
  },
  syncButton: {
    backgroundColor: COLORS.primary,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 12,
    borderRadius: 6,
  },
  syncButtonText: {
    color: '#fff',
    fontSize: SIZES.font,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 32,
  },
  emptyTitle: {
    fontSize: SIZES.large,
    fontWeight: 'bold',
    color: COLORS.text,
    marginTop: 16,
    marginBottom: 8,
  },
  emptyText: {
    fontSize: SIZES.medium,
    color: COLORS.textLight,
    textAlign: 'center',
  },
});

export default RescheduleDeliveryScreen; 