import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SafeAreaView,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { colors, fonts, spacing, borderRadius, shadows } from '../../config/theme';
import { clienteAPI } from '../../config/api';

export default function EntregasScreen() {
  const [entregas, setEntregas] = useState([]);
  const [filtro, setFiltro] = useState('todas');
  const [refreshing, setRefreshing] = useState(false);

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

  const loadEntregas = async () => {
    try {
      const response = await clienteAPI.minhasEntregas();
      if (response.data.success) {
        setEntregas(response.data.entregas || []);
      }
    } catch (error) {
      console.error('Erro ao carregar entregas:', error);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await loadEntregas();
    setRefreshing(false);
  };

  const getStatusInfo = (status) => {
    switch (status) {
      case 'pendente':
        return { color: colors.warning, text: '⏳ Aguardando', bg: '#fff3e0' };
      case 'aceita':
        return { color: colors.info, text: '✅ Aceita', bg: '#e3f2fd' };
      case 'coletada':
        return { color: colors.primary, text: '🚚 Em trânsito', bg: '#e8eaf6' };
      case 'entregue':
        return { color: colors.success, text: '🎉 Entregue', bg: '#e8f5e9' };
      case 'cancelada':
        return { color: colors.danger, text: '❌ Cancelada', bg: '#ffebee' };
      default:
        return { color: colors.gray[500], text: status, bg: colors.gray[100] };
    }
  };

  const filteredEntregas = entregas.filter((e) => {
    if (filtro === 'todas') return true;
    if (filtro === 'ativas') return ['pendente', 'aceita', 'coletada'].includes(e.status);
    if (filtro === 'concluidas') return e.status === 'entregue';
    if (filtro === 'canceladas') return e.status === 'cancelada';
    return true;
  });

  const renderEntrega = ({ item }) => {
    const statusInfo = getStatusInfo(item.status);
    
    return (
      <View style={[styles.card, { borderLeftColor: statusInfo.color }]}>
        <View style={styles.cardHeader}>
          <Text style={styles.cardValor}>
            R$ {parseFloat(item.valor).toFixed(2).replace('.', ',')}
          </Text>
          <View style={[styles.statusBadge, { backgroundColor: statusInfo.bg }]}>
            <Text style={[styles.statusText, { color: statusInfo.color }]}>
              {statusInfo.text}
            </Text>
          </View>
        </View>

        <View style={styles.cardBody}>
          <View style={styles.enderecoRow}>
            <View style={[styles.enderecoIcon, { backgroundColor: colors.success }]}>
              <Text style={styles.enderecoIconText}>A</Text>
            </View>
            <View style={styles.enderecoInfo}>
              <Text style={styles.enderecoLabel}>Coleta</Text>
              <Text style={styles.enderecoText} numberOfLines={2}>
                {item.origem_endereco}
              </Text>
            </View>
          </View>

          <View style={styles.linhaVertical} />

          <View style={styles.enderecoRow}>
            <View style={[styles.enderecoIcon, { backgroundColor: colors.danger }]}>
              <Text style={styles.enderecoIconText}>B</Text>
            </View>
            <View style={styles.enderecoInfo}>
              <Text style={styles.enderecoLabel}>Entrega</Text>
              <Text style={styles.enderecoText} numberOfLines={2}>
                {item.destino_endereco}
              </Text>
            </View>
          </View>
        </View>

        {item.entregador_nome && (
          <View style={styles.cardFooter}>
            <Text style={styles.entregadorText}>
              🏍️ {item.entregador_nome}
            </Text>
            {item.entregador_telefone && (
              <TouchableOpacity>
                <Text style={styles.telefoneText}>📞 Ligar</Text>
              </TouchableOpacity>
            )}
          </View>
        )}

        <View style={styles.cardMeta}>
          <Text style={styles.metaText}>
            📅 {new Date(item.created_at).toLocaleDateString('pt-BR')}
          </Text>
          {item.distancia && (
            <Text style={styles.metaText}>
              📏 {parseFloat(item.distancia).toFixed(1)} km
            </Text>
          )}
          {item.categoria_veiculo && (
            <Text style={styles.metaText}>
              🚗 {item.categoria_veiculo}
            </Text>
          )}
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Minhas Entregas</Text>
        <Text style={styles.headerSubtitle}>{entregas.length} entregas no total</Text>
      </View>

      {/* Filtros */}
      <View style={styles.filtros}>
        {[
          { id: 'todas', label: 'Todas' },
          { id: 'ativas', label: 'Ativas' },
          { id: 'concluidas', label: 'Concluídas' },
          { id: 'canceladas', label: 'Canceladas' },
        ].map((f) => (
          <TouchableOpacity
            key={f.id}
            style={[styles.filtroBtn, filtro === f.id && styles.filtroBtnActive]}
            onPress={() => setFiltro(f.id)}
          >
            <Text style={[styles.filtroText, filtro === f.id && styles.filtroTextActive]}>
              {f.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Lista */}
      <FlatList
        data={filteredEntregas}
        renderItem={renderEntrega}
        keyExtractor={(item) => item.id.toString()}
        contentContainerStyle={styles.lista}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[colors.primary]} />
        }
        ListEmptyComponent={
          <View style={styles.emptyState}>
            <Text style={styles.emptyIcon}>📭</Text>
            <Text style={styles.emptyText}>Nenhuma entrega encontrada</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    backgroundColor: colors.primary,
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.lg,
    paddingTop: spacing.xl,
  },
  headerTitle: {
    fontSize: fonts.sizes.xxl,
    fontWeight: 'bold',
    color: colors.white,
  },
  headerSubtitle: {
    fontSize: fonts.sizes.sm,
    color: 'rgba(255, 255, 255, 0.8)',
    marginTop: 2,
  },
  filtros: {
    flexDirection: 'row',
    backgroundColor: colors.white,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderBottomWidth: 1,
    borderBottomColor: colors.gray[200],
  },
  filtroBtn: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: borderRadius.full,
    marginRight: spacing.sm,
  },
  filtroBtnActive: {
    backgroundColor: colors.primary,
  },
  filtroText: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[600],
  },
  filtroTextActive: {
    color: colors.white,
    fontWeight: '600',
  },
  lista: {
    padding: spacing.lg,
  },
  card: {
    backgroundColor: colors.white,
    borderRadius: borderRadius.lg,
    marginBottom: spacing.md,
    borderLeftWidth: 4,
    ...shadows.sm,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.gray[100],
  },
  cardValor: {
    fontSize: fonts.sizes.xl,
    fontWeight: 'bold',
    color: colors.success,
  },
  statusBadge: {
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    borderRadius: borderRadius.full,
  },
  statusText: {
    fontSize: fonts.sizes.xs,
    fontWeight: '600',
  },
  cardBody: {
    padding: spacing.md,
  },
  enderecoRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  enderecoIcon: {
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  enderecoIconText: {
    color: colors.white,
    fontSize: fonts.sizes.xs,
    fontWeight: 'bold',
  },
  enderecoInfo: {
    flex: 1,
    marginLeft: spacing.sm,
  },
  enderecoLabel: {
    fontSize: fonts.sizes.xs,
    color: colors.gray[500],
  },
  enderecoText: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[800],
  },
  linhaVertical: {
    width: 2,
    height: 16,
    backgroundColor: colors.gray[300],
    marginLeft: 11,
    marginVertical: 4,
  },
  cardFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    backgroundColor: colors.gray[50],
    borderTopWidth: 1,
    borderTopColor: colors.gray[100],
  },
  entregadorText: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[700],
  },
  telefoneText: {
    fontSize: fonts.sizes.sm,
    color: colors.primary,
    fontWeight: '600',
  },
  cardMeta: {
    flexDirection: 'row',
    paddingHorizontal: spacing.md,
    paddingBottom: spacing.md,
    gap: spacing.md,
  },
  metaText: {
    fontSize: fonts.sizes.xs,
    color: colors.gray[500],
  },
  emptyState: {
    alignItems: 'center',
    paddingVertical: spacing.xxxl,
  },
  emptyIcon: {
    fontSize: 48,
    marginBottom: spacing.md,
  },
  emptyText: {
    fontSize: fonts.sizes.md,
    color: colors.gray[500],
  },
});
