import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, ActivityIndicator, RefreshControl, useColorScheme, TouchableOpacity } from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import GlassCard from '@/components/common/GlassCard';
import { Ionicons } from '@expo/vector-icons';
import AnimatedButton from '@/components/common/AnimatedButton';
import { useRouter, useFocusEffect } from 'expo-router';
import { UnifiedBottomNav } from '@/components/home/UnifiedBottomNav';

export default function TicketsScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const router = useRouter();

  const [tickets, setTickets] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchTickets = async () => {
    try {
      const response = await api.post('/ticket/list');
      // API returns: { success: true, data: [...] }
      setTickets(response.data.data || []);
    } catch (error) {
      console.error('Error fetching tickets:', error);
      setTickets([]);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(
    useCallback(() => {
      fetchTickets();
    }, [])
  );

  const onRefresh = () => {
    setRefreshing(true);
    fetchTickets();
  };

  const renderItem = ({ item, index }: { item: any; index: number }) => {
    const isClosed = item.status === 'Closed';
    const statusColor = isClosed ? theme.success : theme.primary;

    return (
      <Animated.View entering={FadeInDown.duration(400).delay(index * 100)}>
        <TouchableOpacity 
          activeOpacity={0.8} 
          onPress={() => router.push({ 
            pathname: '/(drawer)/ticket/[id]' as any, 
            params: { id: item.id, data: JSON.stringify(item) } 
          })}
        >
          <GlassCard intensity={8} style={styles.card}>
            <View style={styles.topRow}>
              <View style={styles.leftInfo}>
                <Text style={[styles.title, { color: theme.text }]} numberOfLines={1}>
                  {item.subject || 'Ticket de Suporte'}
                </Text>
                <Text style={[styles.ticketId, { color: theme.textMuted }]}>
                  ID: {item.ticket_id || item.id}
                </Text>
              </View>
              <View style={[styles.statusBadge, { backgroundColor: `${statusColor}15` }]}>
                <Text style={[styles.statusText, { color: statusColor }]}>
                  {item.status === '1' ? 'Aberto' : item.status === '4' ? 'Fechado' : 'Em Progresso'}
                </Text>
              </View>
            </View>



            <View style={styles.bottomRow}>
              <View style={styles.dateRow}>
                <Ionicons name="time-outline" size={14} color={theme.textMuted} />
                <Text style={[styles.dateText, { paddingLeft: 4, color: theme.textMuted }]}>
                  {item.created_at ? new Date(item.created_at).toLocaleDateString() : '—'}
                </Text>
              </View>
              
              <View style={styles.dateRow}>
                <Text style={[styles.dateText, { color: theme.primary, fontWeight: '600' }]}>Ver Detalhes</Text>
                <Ionicons name="chevron-forward" size={14} color={theme.primary} />
              </View>
            </View>
          </GlassCard>
        </TouchableOpacity>
      </Animated.View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      {loading && !refreshing ? (
        <View style={styles.centerContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
        </View>
      ) : (
        <FlatList
          data={tickets}
          keyExtractor={(item, index) => item.id ? item.id.toString() : index.toString()}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
          ListHeaderComponent={
            <Animated.View entering={FadeIn.duration(400).delay(100)} style={{ marginBottom: 20 }}>
              <AnimatedButton 
                title="Novo Ticket de Suporte" 
                onPress={() => router.push('/(drawer)/ticket/create' as any)} 
              />
            </Animated.View>
          }
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Ionicons name="chatbubbles-outline" size={48} color={theme.border} style={{ marginBottom: 12 }} />
              <Text style={[styles.emptyText, { color: theme.textMuted }]}>Nenhum ticket de suporte encontrado.</Text>
            </View>
          }
        />
      )}
      <UnifiedBottomNav />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  centerContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  listContent: { padding: 20, paddingBottom: 100 },
  card: {
    padding: 16,
    marginBottom: 12,
    borderRadius: 16,
  },
  topRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 8,
  },
  leftInfo: { flex: 1, paddingRight: 10 },
  title: { fontSize: 16, fontWeight: '700', letterSpacing: -0.3, marginBottom: 4 },
  ticketId: { fontSize: 12, fontWeight: '600' },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  statusText: { fontSize: 11, fontWeight: '700' },
  description: {
    fontSize: 14,
    lineHeight: 20,
    marginBottom: 12,
  },
  bottomRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 12,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: 'rgba(150,150,150,0.2)',
  },
  dateRow: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  dateText: { fontSize: 12 },
  emptyContainer: { padding: 40, alignItems: 'center', justifyContent: 'center', marginTop: 30 },
  emptyText: { fontSize: 15 }
});
