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 { entregadorAPI } from '../../config/api';

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

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

  const loadHistorico = async () => {
    try {
      const response = await entregadorAPI.historico();
      if (response.data.success) {
        setEntregas(response.data.entregas || []);
      }
    } catch (error) {
      console.error('Erro ao carregar histórico:', error);
    }
  };

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

  const getStatusInfo = (status) => {
    switch (status) {
      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;
    return e.status === filtro;
  });

  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>
            <Text style={styles.enderecoText} numberOfLines={1}>{item.origem_endereco}</Text>
          </View>
          <View style={styles.linhaVertical} />
          <View style={styles.enderecoRow}>
            <View style={[styles.enderecoIcon, { backgroundColor: colors.danger }]}>
              <Text style={styles.enderecoIconText}>B</Text>
            </View>
            <Text style={styles.enderecoText} numberOfLines={1}>{item.destino_endereco}</Text>
          </View>
        </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>}
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>📋 Histórico</Text>
        <Text style={styles.headerSubtitle}>{entregas.length} entregas realizadas</Text>
      </View>

      <View style={styles.filtros}>
        {[
          { id: 'todas', label: 'Todas' },
          { id: 'entregue', label: 'Entregues' },
          { id: 'cancelada', 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>

      <FlatList
        data={filteredEntregas}
        renderItem={renderEntrega}
        keyExtractor={(item) => item.id.toString()}
        contentContainerStyle={styles.lista}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[colors.entregador.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.entregador.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.entregador.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: 'center' },
  enderecoIcon: { width: 20, height: 20, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  enderecoIconText: { color: colors.white, fontSize: 10, fontWeight: 'bold' },
  enderecoText: { flex: 1, marginLeft: spacing.sm, fontSize: fonts.sizes.sm, color: colors.gray[700] },
  linhaVertical: { width: 2, height: 12, backgroundColor: colors.gray[300], marginLeft: 9, marginVertical: 2 },
  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] },
});