import React, { useEffect, useState, useRef } from 'react';
import { 
  View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity, 
  KeyboardAvoidingView, Platform, ActivityIndicator, useColorScheme 
} from 'react-native';
import { useLocalSearchParams, useRouter, useNavigation } from 'expo-router';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { Ionicons } from '@expo/vector-icons';
import { Image } from 'expo-image';
import { BlurView } from 'expo-blur';
import { LinearGradient } from 'expo-linear-gradient';
import GlassCard from '@/components/common/GlassCard';
import { useAuthStore } from '@/store/authStore';
import Animated, { FadeIn, FadeInRight, FadeInLeft, Layout } from 'react-native-reanimated';

export default function ChatConversationScreen() {
  const { id, name, avatar } = useLocalSearchParams();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const isDark = colorScheme === 'dark';T
  const router = useRouter();
  const navigation = useNavigation();

  const [messages, setMessages] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [inputText, setInputText] = useState('');
  const [sending, setSending] = useState(false);
  const flatListRef = useRef<FlatList>(null);
  const pollingRef = useRef<any>(null);

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

  const fetchMessages = async (isInitial = false) => {
    // Stop if not authenticated or no token to avoid 401 loops
    if (!isAuthenticated || !token || !id) {
      if (pollingRef.current) clearInterval(pollingRef.current);
      return;
    }

    try {
      const response = await api.post('/chat/get-messages', {
        to_user_id: id,
        offset: 0
      });
      const newMessages = response.data.data || [];
      
      setMessages(prev => {
        if (JSON.stringify(prev) !== JSON.stringify(newMessages)) {
          return newMessages;
        }
        return prev;
      });
    } catch (error: any) {
      // If we get a 401, stop polling immediately
      if (error.response?.status === 401) {
        if (pollingRef.current) clearInterval(pollingRef.current);
      }
      console.error('Error fetching messages:', error);
    } finally {
      if (isInitial) setLoading(false);
    }
  };

  useEffect(() => {
    if (!id || !isAuthenticated) return;
    
    fetchMessages(true);
    pollingRef.current = setInterval(() => fetchMessages(), 3000);
    
    return () => {
      if (pollingRef.current) clearInterval(pollingRef.current);
    };
  }, [id, isAuthenticated]);

  const handleSendMessage = async () => {
    if (!inputText.trim() || sending) return;

    setSending(true);
    try {
      const response = await api.post('/chat/send-message', {
        to_user_id: id,
        content: inputText.trim()
      });
      if (response.data.status) {
        setInputText('');
        fetchMessages();
      }
    } catch (error: any) {
      console.error('Error sending message:', error.message);
    } finally {
      setSending(false);
    }
  };

  useEffect(() => {
    navigation.setOptions({
      headerTitle: (name as string) || 'Chat',
      headerLeft: () => (
        <TouchableOpacity onPress={() => router.back()} style={{ marginLeft: 10, padding: 5 }}>
          <Ionicons name="chevron-back" size={28} color="#fff" />
        </TouchableOpacity>
      ),
    });
  }, [name, navigation]);

  const renderMessage = ({ item, index }: { item: any, index: number }) => {
    const isMe = item.position === 'right';
    
    return (
      <Animated.View 
        layout={Layout.springify()}
        entering={isMe ? FadeInRight.duration(400) : FadeInLeft.duration(400)}
        style={[styles.messageWrapper, isMe ? styles.myMessageWrapper : styles.theirMessageWrapper]}
      >
        {!isMe && (
          <Image 
            source={avatar ? { uri: avatar as string } : require('@/assets/images/favicon.png')} 
            style={styles.messageAvatar} 
          />
        )}
        <View style={styles.bubbleContainer}>
          <LinearGradient
            colors={isMe ? ['#6366f1', '#4f46e5'] : isDark ? ['#334155', '#1e293b'] : ['#f1f5f9', '#e2e8f0']}
            style={[styles.messageBubble, isMe ? styles.myBubble : styles.theirBubble]}
          >
            <Text style={[styles.messageText, { color: isMe ? '#FFF' : theme.text }]}>
              {item.content}
            </Text>
          </LinearGradient>
          <Text style={[styles.messageTime, { alignSelf: isMe ? 'flex-end' : 'flex-start' }]}>
            {item.created_at_humantime}
          </Text>
        </View>
      </Animated.View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      
      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
        </View>
      ) : (
        <FlatList
          ref={flatListRef}
          data={messages}
          inverted
          keyExtractor={(item, index) => (item.message_id || index).toString()}
          renderItem={renderMessage}
          contentContainerStyle={styles.messagesList}
          showsVerticalScrollIndicator={false}
        />
      )}

      <KeyboardAvoidingView 
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        <View style={[styles.inputContainerOuter, { backgroundColor: theme.background }]}>
          <View style={styles.inputContainer}>
            <TouchableOpacity style={styles.attachButton}>
              <Ionicons name="add-circle-outline" size={28} color={theme.textMuted} />
            </TouchableOpacity>
            
            <TextInput
              style={[styles.input, { backgroundColor: isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)', color: theme.text }]}
              placeholder="Escreva uma mensagem..."
              placeholderTextColor={theme.textMuted}
              value={inputText}
              onChangeText={setInputText}
              multiline
            />
            
            <TouchableOpacity 
              onPress={handleSendMessage}
              disabled={!inputText.trim() || sending}
              style={[styles.sendButton, { opacity: !inputText.trim() ? 0.5 : 1 }]}
            >
              <LinearGradient colors={['#6366f1', '#4f46e5']} style={styles.sendButtonGradient}>
                {sending ? (
                  <ActivityIndicator size="small" color="#FFF" />
                ) : (
                  <Ionicons name="send" size={20} color="#FFF" />
                )}
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </View>
      </KeyboardAvoidingView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  messagesList: { padding: 16, paddingTop: 10, paddingBottom: 20 },
  messageWrapper: { flexDirection: 'row', marginBottom: 16, maxWidth: '85%' },
  myMessageWrapper: { alignSelf: 'flex-end' },
  theirMessageWrapper: { alignSelf: 'flex-start' },
  messageAvatar: { width: 32, height: 32, borderRadius: 16, alignSelf: 'flex-end', marginRight: 8 },
  bubbleContainer: { flexShrink: 1 },
  messageBubble: { padding: 12, borderRadius: 20, shadowColor: 'transparent', elevation: 0 },
  myBubble: { borderBottomRightRadius: 4 },
  theirBubble: { borderBottomLeftRadius: 4 },
  messageText: { fontSize: 16, lineHeight: 22, fontWeight: '400' },
  messageTime: { fontSize: 10, color: '#94a3b8', marginTop: 4, marginHorizontal: 4 },
  inputContainerOuter: { 
    paddingBottom: Platform.OS === 'ios' ? 40 : 20, 
    paddingTop: 15, 
    paddingHorizontal: 16, 
    borderTopWidth: 1, 
    borderTopColor: 'rgba(150,150,150,0.1)' 
  },
  inputContainer: { flexDirection: 'row', alignItems: 'center' },
  attachButton: { marginRight: 10 },
  input: { flex: 1, borderRadius: 24, paddingHorizontal: 16, paddingVertical: 10, maxHeight: 100, fontSize: 16 },
  sendButton: { marginLeft: 10 },
  sendButtonGradient: { width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' }
});
