import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { COLORS, SHADOWS } from '../constants/theme';
import { Delivery } from '../types';
import { api } from '../services/api';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface DebugPanelProps {
  isVisible: boolean;
  onToggle: () => void;
}

const DebugPanel: React.FC<DebugPanelProps> = ({ isVisible, onToggle }) => {
  const [deliveries, setDeliveries] = useState<Delivery[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);

  // Carregar entregas para debug
  const loadDeliveriesForDebug = async () => {
    try {
      setIsLoading(true);
      const response = await api.request('/v1/driver/deliveries');
      if (response) {
        const deliveriesData = Array.isArray(response) ? response : [];
        setDeliveries(deliveriesData);
        setLastUpdate(new Date());
      }
    } catch (error) {
      console.error('Erro ao carregar entregas para debug:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // Verificar token
  const checkToken = async () => {
    try {
      const token = await AsyncStorage.getItem('authToken');
      if (token) {
        Alert.alert('Token', `Token encontrado: ${token.substring(0, 20)}...`);
      } else {
        Alert.alert('Token', 'Nenhum token encontrado');
      }
    } catch (error) {
      Alert.alert('Erro', 'Erro ao verificar token');
    }
  };

  // Testar endpoint de roteirização
  const testRoutingEndpoint = async () => {
    try {
      const token = await AsyncStorage.getItem('authToken');
      if (!token) {
        Alert.alert('Erro', 'Token não encontrado');
        return;
      }

      // Dados de teste
      const testData = [{
        outId: 'TEST001',
        customerId: 123,
        deliverySeq: 1,
        lat: -1.3654,
        lng: -48.3722
      }];

      Alert.alert('Teste', `Testando endpoint com dados: ${JSON.stringify(testData, null, 2)}`);
      
      const response = await api.request<{ success: boolean; message: string }>('/v1/driver/routing', {
        method: 'POST',
        body: JSON.stringify(testData)
      });

      Alert.alert('Resposta', `Resposta: ${JSON.stringify(response, null, 2)}`);
    } catch (error: any) {
      Alert.alert('Erro', `Erro: ${error.message}`);
    }
  };

  useEffect(() => {
    if (isVisible) {
      loadDeliveriesForDebug();
    }
  }, [isVisible]);

  if (!isVisible) return null;

  return (
    <View style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>🔍 Painel de Debug</Text>
        <TouchableOpacity onPress={onToggle} style={styles.closeButton}>
          <Ionicons name="close" size={24} color="white" />
        </TouchableOpacity>
      </View>

      {/* Controles */}
      <View style={styles.controls}>
        <TouchableOpacity 
          style={styles.controlButton} 
          onPress={loadDeliveriesForDebug}
          disabled={isLoading}
        >
          <Ionicons name="refresh" size={16} color="white" />
          <Text style={styles.controlButtonText}>
            {isLoading ? 'Carregando...' : 'Recarregar'}
          </Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={styles.controlButton} 
          onPress={checkToken}
        >
          <Ionicons name="key" size={16} color="white" />
          <Text style={styles.controlButtonText}>Verificar Token</Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={styles.controlButton} 
          onPress={testRoutingEndpoint}
        >
          <Ionicons name="bug" size={16} color="white" />
          <Text style={styles.controlButtonText}>Testar Roteirização</Text>
        </TouchableOpacity>
      </View>

      {/* Status */}
      <View style={styles.statusSection}>
        <Text style={styles.sectionTitle}>📊 Status Geral</Text>
        <View style={styles.statusGrid}>
          <View style={styles.statusItem}>
            <Text style={styles.statusNumber}>{deliveries.length}</Text>
            <Text style={styles.statusLabel}>Total</Text>
          </View>
          <View style={styles.statusItem}>
            <Text style={styles.statusNumber}>
              {deliveries.filter(d => d.routing === 0).length}
            </Text>
            <Text style={styles.statusLabel}>Sem Roteirização</Text>
          </View>
          <View style={styles.statusItem}>
            <Text style={styles.statusNumber}>
              {deliveries.filter(d => d.routing === 1).length}
            </Text>
            <Text style={styles.statusLabel}>Roteirizadas</Text>
          </View>
          <View style={styles.statusItem}>
            <Text style={styles.statusNumber}>
              {deliveries.filter(d => d.deliverySeq).length}
            </Text>
            <Text style={styles.statusLabel}>Com Sequência</Text>
          </View>
        </View>
        
        {lastUpdate && (
          <Text style={styles.lastUpdate}>
            Última atualização: {lastUpdate.toLocaleTimeString()}
          </Text>
        )}
      </View>

      {/* Lista de Entregas */}
      <ScrollView style={styles.deliveriesList}>
        <Text style={styles.sectionTitle}>📦 Detalhes das Entregas</Text>
        {deliveries.map((delivery, index) => (
          <View key={delivery.id || index} style={styles.deliveryItem}>
            <View style={styles.deliveryHeader}>
              <Text style={styles.deliveryNumber}>#{delivery.outId}</Text>
              <View style={[
                styles.routingBadge, 
                { backgroundColor: delivery.routing === 1 ? COLORS.success : COLORS.warning }
              ]}>
                <Text style={styles.routingText}>
                  {delivery.routing === 1 ? 'Roteirizada' : 'Sem Roteirização'}
                </Text>
              </View>
            </View>
            
            <Text style={styles.customerName}>{delivery.customerName}</Text>
            
            <View style={styles.deliveryDetails}>
              <Text style={styles.detailText}>
                <Text style={styles.detailLabel}>Sequência:</Text> {delivery.deliverySeq || 'N/A'}
              </Text>
              <Text style={styles.detailText}>
                <Text style={styles.detailLabel}>Status:</Text> {delivery.status}
              </Text>
              <Text style={styles.detailText}>
                <Text style={styles.detailLabel}>Coordenadas:</Text> {delivery.lat}, {delivery.lng}
              </Text>
              <Text style={styles.detailText}>
                <Text style={styles.detailLabel}>Routing:</Text> {delivery.routing}
              </Text>
            </View>
          </View>
        ))}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.9)',
    zIndex: 1000,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: COLORS.primary,
    padding: 20,
    paddingTop: 50,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: 'white',
  },
  closeButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  controls: {
    flexDirection: 'row',
    padding: 20,
    gap: 10,
  },
  controlButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.secondary,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    gap: 6,
  },
  controlButtonText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '500',
  },
  statusSection: {
    backgroundColor: 'white',
    margin: 20,
    padding: 20,
    borderRadius: 12,
    ...SHADOWS.medium,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text,
    marginBottom: 16,
  },
  statusGrid: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 16,
  },
  statusItem: {
    alignItems: 'center',
  },
  statusNumber: {
    fontSize: 20,
    fontWeight: 'bold',
    color: COLORS.primary,
  },
  statusLabel: {
    fontSize: 10,
    color: COLORS.textLight,
    marginTop: 4,
    textAlign: 'center',
  },
  lastUpdate: {
    fontSize: 12,
    color: COLORS.textLight,
    textAlign: 'center',
    fontStyle: 'italic',
  },
  deliveriesList: {
    flex: 1,
    margin: 20,
    marginTop: 0,
  },
  deliveryItem: {
    backgroundColor: 'white',
    padding: 16,
    marginBottom: 12,
    borderRadius: 12,
    ...SHADOWS.small,
  },
  deliveryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  deliveryNumber: {
    fontSize: 14,
    fontWeight: '600',
    color: COLORS.primary,
  },
  routingBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  routingText: {
    fontSize: 10,
    fontWeight: '500',
    color: 'white',
  },
  customerName: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text,
    marginBottom: 8,
  },
  deliveryDetails: {
    gap: 4,
  },
  detailText: {
    fontSize: 12,
    color: COLORS.textLight,
  },
  detailLabel: {
    fontWeight: '500',
    color: COLORS.text,
  },
});

export default DebugPanel; 