import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  TextInput, 
  StyleSheet, 
  KeyboardAvoidingView, 
  Platform,
  Dimensions
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import LottieView from 'lottie-react-native';
import { HistoricalFigure, Message } from '../types/types';
import { fetchAIResponse } from '../services/openaiService';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import MessageItem from '../components/MessageItem';
import { Ionicons } from '@expo/vector-icons';
import CustomText from '../components/CustomText';

interface RouteParams {
  chatId: string;
  figure: HistoricalFigure;
}

interface APIMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

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

const ChatScreen = () => {
  const navigation = useNavigation();
  const route = useRoute();
  const { chatId, figure } = route.params as RouteParams;
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState<string>('');
  const [isTyping, setIsTyping] = useState<boolean>(false);
  const flatListRef = useRef<FlatList>(null);

  useEffect(() => {
    const loadMessages = async () => {
      try {
        const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
        const msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];
        setMessages(msgs);
      } catch (error) {
        console.error('Error loading messages:', error);
      }
    };

    loadMessages();
  }, [chatId]);

  const saveMessages = useCallback(async (updatedMessages: Message[]) => {
    try {
      await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
    } catch (error) {
      console.error('Error saving messages:', error);
    }
  }, [chatId]);

  const sendMessage = useCallback(async () => {
    if (inputText.trim() === '') return;

    const userMessage: Message = {
      id: uuid.v4().toString(),
      text: inputText,
      isUser: true,
      timestamp: Date.now(),
    };
    const updatedMessages = [userMessage, ...messages];
    setMessages(updatedMessages);
    setInputText('');
    setIsTyping(true);

    await saveMessages(updatedMessages);

    const apiMessages: APIMessage[] = [
      {
        role: 'system',
        content: figure.systemPrompt,
      },
      ...updatedMessages.map(msg => ({
        role: msg.isUser ? 'user' : 'assistant',
        content: msg.text,
      })),
    ];

    try {
      const aiResponse = await fetchAIResponse(apiMessages);

      const aiMessage: Message = {
        id: uuid.v4().toString(),
        text: aiResponse,
        isUser: false,
        timestamp: Date.now(),
      };

      const newMessages = [aiMessage, ...updatedMessages];
      setMessages(newMessages);
      await saveMessages(newMessages);
    } catch (error) {
      console.error('Error fetching AI response:', error);
    } finally {
      setIsTyping(false);
      flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
    }
  }, [inputText, messages, figure.systemPrompt, saveMessages]);

  const renderMessageItem = useCallback(({ item }: { item: Message }) => (
    <MessageItem message={item} />
  ), []);

  const keyExtractor = useCallback((item: Message) => item.id, []);

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
    >
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
          <Ionicons name="arrow-back" size={28} color="#000" />
        </TouchableOpacity>
        <Image source={{ uri: figure.image }} style={styles.headerAvatar} />
        <View style={styles.headerInfo}>
          <CustomText bold style={styles.headerName}>{figure.name}</CustomText>
          <CustomText style={styles.headerDescription} numberOfLines={1}>
            {figure.description}
          </CustomText>
        </View>
      </View>

      <FlatList
        ref={flatListRef}
        data={messages}
        renderItem={renderMessageItem}
        keyExtractor={keyExtractor}
        style={styles.messageList}
        contentContainerStyle={styles.messageListContent}
        inverted
      />

      {isTyping && (
        <View style={styles.typingIndicator}>
          <LottieView
            source={require('../../assets/typing-animation.json')}
            autoPlay
            loop
            style={styles.typingAnimation}
          />
        </View>
      )}

      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          value={inputText}
          onChangeText={setInputText}
          placeholder="Mesajınızı yazın..."
          onSubmitEditing={sendMessage}
          returnKeyType="send"
        />
        <TouchableOpacity onPress={sendMessage} style={styles.sendButton}>
          <Ionicons name="send" size={24} color="#fff" />
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    paddingTop: Platform.OS === 'ios' ? 50 : 30,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
    backgroundColor: '#FFFFFF',
  },
  backButton: {
    marginRight: 10,
  },
  headerAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
  },
  headerInfo: {
    flex: 1,
  },
  headerName: {
    fontSize: 18,
    color: '#000000',
    fontFamily: 'Roboto_700Bold',
  },
  headerDescription: {
    fontSize: 14,
    color: '#666666',
    marginTop: 2,
    fontFamily: 'Roboto_400Regular',
  },
  messageList: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  messageListContent: {
    paddingVertical: 20,
    paddingHorizontal: 15,
  },
  typingIndicator: {
    position: 'absolute',
    bottom: 70,
    left: 20,
  },
  typingAnimation: {
    width: 80,
    height: 40,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E0E0E0',
  },
  input: {
    flex: 1,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#F0F0F0',
    paddingHorizontal: 15,
    marginRight: 10,
    fontFamily: 'Roboto_400Regular',
  },
  sendButton: {
    backgroundColor: '#007AFF',
    borderRadius: 20,
    padding: 10,
  },
});

export default ChatScreen; bu sayfada bir sıkıntı yaşıyoruz. hangi mesaj aiye iletildi loglarda göster bana. sanki hangi mesaja cevap verdiği biraz karışmış gibi.