import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, ActivityIndicator, RefreshControl, useColorScheme } from 'react-native';
import { Image } from 'expo-image';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useRouter, useFocusEffect, useNavigation } from 'expo-router';
import { useAuthStore } from '@/store/authStore';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { BlurView } from 'expo-blur';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';

const GENTLE_GRADIENTS = [
  ['#6366f1', '#a855f7'],
  ['#ec4899', '#f43f5e'],
  ['#3b82f6', '#2dd4bf'],
  ['#f59e0b', '#ef4444'],
];

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

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

  const fetchChats = async () => {
    try {
      const response = await api.get('/chat/list');
      setChats(response.data.data || []);
    } catch (error) {
      console.error('Error fetching chats:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const isAuthenticated = useAuthStore((state: any) => state.isAuthenticated);
  const token = useAuthStore((state: any) => state.token);

  useFocusEffect(
    useCallback(() => {
      if (!isAuthenticated || !token) return;
      
      fetchChats();
      const interval = setInterval(fetchChats, 8000);
      return () => clearInterval(interval);
    }, [navigation, isAuthenticated, token])
  );

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

  const getAvatarFallback = (name: string, index: number) => {
    const initials = (name || '?').split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
    const gradient = GENTLE_GRADIENTS[index % GENTLE_GRADIENTS.length];
    
    return (
      <LinearGradient colors={gradient as any} style={styles.avatarFallback}>
        <Text style={styles.avatarFallbackText}>{initials}</Text>
      </LinearGradient>
    );
  };

  const renderChatItem = ({ item, index }: { item: any; index: number }) => {
    const lastMsg = item.last_message?.message || 'Inicie uma conversa';
    const time = item.last_message?.created_at_humantime || '';
    
    return (
      <Animated.View entering={FadeInDown.duration(400).delay(index * 80)}>
        <TouchableOpacity 
          onPress={() => router.push({ 
            pathname: '/(drawer)/chat/[id]', 
            params: { id: item.user_id, name: item.fullname || item.username, avatar: item.profile_image } 
          } as any)}
          activeOpacity={0.7}
          style={styles.chatItemOuter}
        >
          <View style={[styles.chatItem, { backgroundColor: isDark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.95)' }]}>
            <View style={styles.avatarContainer}>
              {item.profile_image ? (
                <Image source={{ uri: item.profile_image }} style={styles.avatar} contentFit="cover" transition={200} />
              ) : (
                getAvatarFallback(item.fullname || item.username || 'Usuario', index)
              )}
              <View style={[styles.statusDot, { backgroundColor: '#10b981', borderColor: isDark ? '#1a1a1a' : '#fff' }]} />
            </View>

            <View style={styles.chatInfo}>
              <View style={styles.chatHeader}>
                <Text style={[styles.userName, { color: theme.text }]} numberOfLines={1}>{item.fullname || item.username}</Text>
                <Text style={[styles.chatTime, { color: theme.textMuted }]}>{time}</Text>
              </View>
              
              <View style={styles.messageRow}>
                <Text 
                  style={[
                    styles.lastMessage, 
                    { color: item.unread_count > 0 ? theme.text : theme.textMuted, 
                      fontWeight: item.unread_count > 0 ? '700' : '400' }
                  ]} 
                  numberOfLines={1}
                >
                  {lastMsg}
                </Text>
                {item.unread_count > 0 && (
                  <LinearGradient colors={['#6366f1', '#8b5cf6'] as any} style={styles.unreadBadge}>
                    <Text style={styles.unreadText}>{item.unread_count}</Text>
                  </LinearGradient>
                )}
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <LinearGradient 
        colors={isDark ? ['#1a1a1a', '#0f172a'] as any : ['#f1f5f9', '#ffffff'] as any} 
        style={StyleSheet.absoluteFill} 
      />
      
      {loading && !refreshing ? (
        <View style={styles.loaderContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
        </View>
      ) : (
        <FlatList
          data={chats}
          keyExtractor={(item) => item.user_id.toString()}
          renderItem={renderChatItem}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />}
          ListEmptyComponent={
            <Animated.View entering={FadeIn.delay(300)} style={styles.emptyContainer}>
              <View style={styles.emptyIconContainer}>
                <Ionicons name="chatbubbles-outline" size={80} color={theme.primary} style={{ opacity: 0.2 }} />
              </View>
              <Text style={[styles.emptyTitle, { color: theme.text }]}>Silêncio por aqui...</Text>
              <Text style={[styles.emptyText, { color: theme.textMuted }]}>
                Ainda não tens conversas ativas. Contacta um prestador para começar!
              </Text>
            </Animated.View>
          }
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  listContent: { padding: 16, paddingBottom: 100, paddingTop: 10 },
  chatItemOuter: {
    marginBottom: 12,
    borderRadius: 24,
    borderWidth: 1,
    borderColor: 'rgba(150,150,150,0.1)',
  },
  chatItem: { 
    flexDirection: 'row', 
    alignItems: 'center', 
    padding: 14, 
    borderRadius: 24,
  },
  avatarContainer: { position: 'relative' },
  avatar: { width: 60, height: 60, borderRadius: 30, backgroundColor: 'rgba(150,150,150,0.1)' },
  avatarFallback: { 
    width: 60, 
    height: 60, 
    borderRadius: 30, 
    justifyContent: 'center', 
    alignItems: 'center',
  },
  avatarFallbackText: { color: '#fff', fontSize: 20, fontWeight: '800', letterSpacing: 1 },
  statusDot: { 
    position: 'absolute', 
    bottom: 2, 
    right: 2, 
    width: 14, 
    height: 14, 
    borderRadius: 7, 
    borderWidth: 2 
  },
  chatInfo: { flex: 1, marginLeft: 16 },
  chatHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 },
  userName: { fontSize: 17, fontWeight: '800', letterSpacing: -0.5 },
  chatTime: { fontSize: 12, fontWeight: '500' },
  messageRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  lastMessage: { fontSize: 14, flex: 1, marginRight: 10 },
  unreadBadge: { 
    minWidth: 22, 
    height: 22, 
    borderRadius: 11, 
    justifyContent: 'center', 
    alignItems: 'center',
    paddingHorizontal: 6,
  },
  unreadText: { color: '#fff', fontSize: 10, fontWeight: '900' },
  emptyContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 120, paddingHorizontal: 40 },
  emptyIconContainer: { 
    width: 120, 
    height: 120, 
    borderRadius: 60, 
    backgroundColor: 'rgba(99, 102, 241, 0.05)', 
    justifyContent: 'center', 
    alignItems: 'center',
    marginBottom: 24
  },
  emptyTitle: { fontSize: 22, fontWeight: '800', marginBottom: 8, letterSpacing: -0.5 },
  emptyText: { fontSize: 15, textAlign: 'center', lineHeight: 22, opacity: 0.8 }
});
