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

const { width } = Dimensions.get('window');

// Componente de Banner Carousel
function BannerCarousel({ banners }) {
  const [activeIndex, setActiveIndex] = useState(0);
  const flatListRef = useRef(null);

  useEffect(() => {
    if (banners.length > 1) {
      const interval = setInterval(() => {
        const nextIndex = (activeIndex + 1) % banners.length;
        setActiveIndex(nextIndex);
        flatListRef.current?.scrollToIndex({ index: nextIndex, animated: true });
      }, 4000);
      return () => clearInterval(interval);
    }
  }, [activeIndex, banners.length]);

  const renderBanner = ({ item }) => (
    <View style={[styles.bannerItem, { backgroundColor: item.cor_fundo || colors.primary }]}>
      <Text style={[styles.bannerTitle, { color: item.cor_texto || colors.white }]}>
        {item.titulo}
      </Text>
      {item.descricao && (
        <Text style={[styles.bannerDesc, { color: item.cor_texto || colors.white }]}>
          {item.descricao}
        </Text>
      )}
    </View>
  );

  if (!banners || banners.length === 0) {
    return (
      <View style={[styles.bannerItem, { backgroundColor: colors.primary }]}>
        <Text style={styles.bannerTitle}>Bem-vindo ao Já EntreGo! 🚚</Text>
        <Text style={styles.bannerDesc}>Entregas rápidas e seguras</Text>
      </View>
    );
  }

  return (
    <View>
      <FlatList
        ref={flatListRef}
        data={banners}
        renderItem={renderBanner}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onMomentumScrollEnd={(e) => {
          const index = Math.round(e.nativeEvent.contentOffset.x / (width - 32));
          setActiveIndex(index);
        }}
        keyExtractor={(item, index) => index.toString()}
      />
      {banners.length > 1 && (
        <View style={styles.indicators}>
          {banners.map((_, index) => (
            <View
              key={index}
              style={[
                styles.indicator,
                activeIndex === index && styles.indicatorActive,
              ]}
            />
          ))}
        </View>
      )}
    </View>
  );
}

// Componente de Card de Entrega
function EntregaCard({ entrega }) {
  const getStatusColor = (status) => {
    switch (status) {
      case 'pendente': return colors.warning;
      case 'aceita': return colors.info;
      case 'coletada': return colors.primary;
      case 'entregue': return colors.success;
      case 'cancelada': return colors.danger;
      default: return colors.gray[500];
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'pendente': return '⏳ Aguardando';
      case 'aceita': return '✅ Aceita';
      case 'coletada': return '🚚 Em trânsito';
      case 'entregue': return '🎉 Entregue';
      case 'cancelada': return '❌ Cancelada';
      default: return status;
    }
  };

  return (
    <View style={styles.entregaCard}>
      <View style={styles.entregaHeader}>
        <Text style={styles.entregaValor}>R$ {parseFloat(entrega.valor).toFixed(2).replace('.', ',')}</Text>
        <View style={[styles.statusBadge, { backgroundColor: getStatusColor(entrega.status) }]}>
          <Text style={styles.statusText}>{getStatusText(entrega.status)}</Text>
        </View>
      </View>
      
      <View style={styles.rotaContainer}>
        <View style={styles.rotaPonto}>
          <View style={[styles.rotaIcon, { backgroundColor: colors.success }]}>
            <Text style={styles.rotaIconText}>A</Text>
          </View>
          <View style={styles.rotaInfo}>
            <Text style={styles.rotaLabel}>Coleta</Text>
            <Text style={styles.rotaEndereco} numberOfLines={1}>{entrega.origem_endereco}</Text>
          </View>
        </View>
        
        <View style={styles.rotaLinha} />
        
        <View style={styles.rotaPonto}>
          <View style={[styles.rotaIcon, { backgroundColor: colors.danger }]}>
            <Text style={styles.rotaIconText}>B</Text>
          </View>
          <View style={styles.rotaInfo}>
            <Text style={styles.rotaLabel}>Entrega</Text>
            <Text style={styles.rotaEndereco} numberOfLines={1}>{entrega.destino_endereco}</Text>
          </View>
        </View>
      </View>

      {entrega.entregador_nome && (
        <View style={styles.entregadorInfo}>
          <Text style={styles.entregadorLabel}>🏍️ Entregador:</Text>
          <Text style={styles.entregadorNome}>{entrega.entregador_nome}</Text>
        </View>
      )}
    </View>
  );
}

export default function DashboardScreen({ navigation }) {
  const [usuario, setUsuario] = useState(null);
  const [entregas, setEntregas] = useState([]);
  const [banners, setBanners] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    loadData();
    loadUserData();
  }, []);

  const loadUserData = async () => {
    try {
      const data = await AsyncStorage.getItem('clienteData');
      if (data) {
        setUsuario(JSON.parse(data));
      }
    } catch (error) {
      console.error('Erro ao carregar dados do usuário:', error);
    }
  };

  const loadData = async () => {
    try {
      // Carregar entregas
      const entregasRes = await clienteAPI.minhasEntregas();
      if (entregasRes.data.success) {
        setEntregas(entregasRes.data.entregas || []);
      }

      // Carregar banners
      const bannersRes = await clienteAPI.getBanners();
      if (bannersRes.data.success) {
        setBanners(bannersRes.data.banners || []);
      }
    } catch (error) {
      console.error('Erro ao carregar dados:', error);
    }
  };

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

  const entregasAtivas = entregas.filter(e => ['pendente', 'aceita', 'coletada'].includes(e.status));

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <View>
          <Text style={styles.greeting}>Olá, {usuario?.nome?.split(' ')[0] || 'Cliente'}! 👋</Text>
          <Text style={styles.subGreeting}>O que deseja enviar hoje?</Text>
        </View>
        <TouchableOpacity style={styles.notificationBtn}>
          <Text style={styles.notificationIcon}>🔔</Text>
        </TouchableOpacity>
      </View>

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[colors.primary]} />
        }
      >
        {/* Banner Carousel */}
        <BannerCarousel banners={banners} />

        {/* Botão Nova Entrega */}
        <TouchableOpacity
          style={styles.novaEntregaBtn}
          onPress={() => navigation.navigate('NovaEntrega')}
        >
          <Text style={styles.novaEntregaIcon}>📦</Text>
          <View style={styles.novaEntregaText}>
            <Text style={styles.novaEntregaTitle}>Nova Entrega</Text>
            <Text style={styles.novaEntregaSubtitle}>Solicite uma entrega agora</Text>
          </View>
          <Text style={styles.novaEntregaArrow}>→</Text>
        </TouchableOpacity>

        {/* Entregas Ativas */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>
            Entregas Ativas ({entregasAtivas.length})
          </Text>
          
          {entregasAtivas.length === 0 ? (
            <View style={styles.emptyState}>
              <Text style={styles.emptyIcon}>📭</Text>
              <Text style={styles.emptyText}>Nenhuma entrega ativa</Text>
              <Text style={styles.emptySubtext}>Solicite uma nova entrega!</Text>
            </View>
          ) : (
            entregasAtivas.map((entrega, index) => (
              <EntregaCard key={entrega.id || index} entrega={entrega} />
            ))
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: colors.primary,
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.lg,
    paddingTop: spacing.xl,
  },
  greeting: {
    fontSize: fonts.sizes.xl,
    fontWeight: 'bold',
    color: colors.white,
  },
  subGreeting: {
    fontSize: fonts.sizes.sm,
    color: 'rgba(255, 255, 255, 0.8)',
    marginTop: 2,
  },
  notificationBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  notificationIcon: {
    fontSize: 20,
  },
  content: {
    flex: 1,
    padding: spacing.lg,
  },
  bannerItem: {
    width: width - 32,
    height: 140,
    borderRadius: borderRadius.xl,
    padding: spacing.xl,
    justifyContent: 'center',
  },
  bannerTitle: {
    fontSize: fonts.sizes.xl,
    fontWeight: 'bold',
    marginBottom: spacing.xs,
  },
  bannerDesc: {
    fontSize: fonts.sizes.md,
    opacity: 0.9,
  },
  indicators: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: spacing.sm,
  },
  indicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: colors.gray[300],
    marginHorizontal: 4,
  },
  indicatorActive: {
    backgroundColor: colors.primary,
    width: 20,
  },
  novaEntregaBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.white,
    borderRadius: borderRadius.xl,
    padding: spacing.lg,
    marginTop: spacing.lg,
    ...shadows.md,
  },
  novaEntregaIcon: {
    fontSize: 36,
    marginRight: spacing.md,
  },
  novaEntregaText: {
    flex: 1,
  },
  novaEntregaTitle: {
    fontSize: fonts.sizes.lg,
    fontWeight: 'bold',
    color: colors.gray[900],
  },
  novaEntregaSubtitle: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[500],
  },
  novaEntregaArrow: {
    fontSize: fonts.sizes.xxl,
    color: colors.primary,
  },
  section: {
    marginTop: spacing.xl,
  },
  sectionTitle: {
    fontSize: fonts.sizes.lg,
    fontWeight: 'bold',
    color: colors.gray[900],
    marginBottom: spacing.md,
  },
  emptyState: {
    backgroundColor: colors.white,
    borderRadius: borderRadius.xl,
    padding: spacing.xxl,
    alignItems: 'center',
    ...shadows.sm,
  },
  emptyIcon: {
    fontSize: 48,
    marginBottom: spacing.md,
  },
  emptyText: {
    fontSize: fonts.sizes.lg,
    fontWeight: '600',
    color: colors.gray[700],
  },
  emptySubtext: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[500],
    marginTop: spacing.xs,
  },
  entregaCard: {
    backgroundColor: colors.white,
    borderRadius: borderRadius.xl,
    padding: spacing.lg,
    marginBottom: spacing.md,
    ...shadows.sm,
  },
  entregaHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
  },
  entregaValor: {
    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',
    color: colors.white,
  },
  rotaContainer: {
    marginBottom: spacing.md,
  },
  rotaPonto: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  rotaIcon: {
    width: 28,
    height: 28,
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',
  },
  rotaIconText: {
    color: colors.white,
    fontWeight: 'bold',
    fontSize: fonts.sizes.sm,
  },
  rotaInfo: {
    flex: 1,
    marginLeft: spacing.sm,
  },
  rotaLabel: {
    fontSize: fonts.sizes.xs,
    color: colors.gray[500],
  },
  rotaEndereco: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[800],
  },
  rotaLinha: {
    width: 2,
    height: 20,
    backgroundColor: colors.gray[300],
    marginLeft: 13,
    marginVertical: 4,
  },
  entregadorInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: spacing.sm,
    borderTopWidth: 1,
    borderTopColor: colors.gray[200],
  },
  entregadorLabel: {
    fontSize: fonts.sizes.sm,
    color: colors.gray[600],
  },
  entregadorNome: {
    fontSize: fonts.sizes.sm,
    fontWeight: '600',
    color: colors.gray[800],
    marginLeft: spacing.xs,
  },
});
