import React, { useEffect, useState, useCallback, useContext } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  Alert,
  SafeAreaView,
  Platform,
  StatusBar as RNStatusBar,
  ActivityIndicator,
  useWindowDimensions
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import { db } from '../services/firebaseConfig';
import { collection, getDocs } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext'; // Existing useApp hook
import { ChatContext } from '../context/ChatContext'; // Import ChatContext

const STORAGE_KEY_FIGURES = 'historical_figures';
const STORAGE_KEY_FIGURES_TIMESTAMP = 'historical_figures_timestamp';
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 1 day in milliseconds

const HomeScreen = () => {
  const navigation = useNavigation();
  const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const { width } = useWindowDimensions();
  const { t, currentTheme } = useApp(); // Existing useApp hook

  // Import addChat from ChatContext
  const { addChat } = useContext(ChatContext);

  // Set numColumns to 2 for a two-column grid
  const numColumns = 2;

  useEffect(() => {
    const loadFigures = async () => {
      try {
        const [cachedFigures, cachedTimestamp] = await Promise.all([
          AsyncStorage.getItem(STORAGE_KEY_FIGURES),
          AsyncStorage.getItem(STORAGE_KEY_FIGURES_TIMESTAMP),
        ]);

        const now = Date.now();
        const isCacheValid = cachedFigures && cachedTimestamp && (now - parseInt(cachedTimestamp, 10) < CACHE_DURATION);

        if (isCacheValid) {
          const figuresList: HistoricalFigure[] = JSON.parse(cachedFigures);
          setHistoricalFigures(figuresList);
        } else {
          await fetchFiguresFromFirebase();
        }
      } catch (error) {
        console.error('Error loading figures:', error);
        Alert.alert(t('error'), t('errorLoadingFigures'));
      } finally {
        setLoading(false);
      }
    };

    loadFigures();
  }, [t]);

  const fetchFiguresFromFirebase = async () => {
    try {
      const figuresCollection = collection(db, 'figures');
      const figuresSnapshot = await getDocs(figuresCollection);
      const figuresList: HistoricalFigure[] = figuresSnapshot.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          name: data.name,
          image: data.image,
          systemPrompt: data.systemPrompt,
          description: data.description || "",
        } as HistoricalFigure;
      });
      setHistoricalFigures(figuresList);
      const now = Date.now();
      await Promise.all([
        AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(figuresList)),
        AsyncStorage.setItem(STORAGE_KEY_FIGURES_TIMESTAMP, now.toString()),
      ]);
    } catch (error) {
      console.error('Error fetching figures:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
    }
  };

  // Start Chat function updated to use ChatContext's addChat
  const startChat = async (figure: HistoricalFigure) => {
    const chatId = uuid.v4().toString();
    const newChat: Chat = {
      id: chatId,
      figure: {
        ...figure,
        description: figure.description || "",
      },
      createdAt: Date.now(),
    };

    const initialMessage: Message = {
      id: uuid.v4().toString(),
      text: figure.description || t('noDescriptionAvailable'),
      isUser: false,
      timestamp: Date.now(),
    };

    try {
      // ChatContext üzerinden sohbeti ekleyin
      await addChat(newChat, [initialMessage]);

      console.log('Chat eklendi:', newChat);
      console.log('İlk mesaj eklendi:', initialMessage);

      // Sohbet ekranına yönlendirin
      navigation.navigate('Chat', { chatId, figure });
    } catch (error) {
      console.error('Error starting chat:', error);
      Alert.alert(t('error'), t('errorStartingChat'));
    }
  };

  const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
    <TouchableOpacity
      style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
      onPress={() => startChat(item)}
    >
      <Image source={{ uri: item.image }} style={styles.avatar} />
      <View style={styles.figureInfo}>
        <CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>{item.name}</CustomText>
        <CustomText style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]} numberOfLines={2}>
          {item.description}
        </CustomText>
      </View>
    </TouchableOpacity>
  ), [currentTheme, startChat]);

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

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
      <StatusBar style={currentTheme.statusBarStyle} />
      <View style={styles.container}>
        <View style={styles.header}>
          <CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>{t('historicalFigures')}</CustomText>
          <TouchableOpacity 
            style={styles.settingsButton} 
            onPress={() => navigation.navigate('Settings')}
          >
            <Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
          </TouchableOpacity>
        </View>
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={currentTheme.accentColor} />
          </View>
        ) : (
          <FlatList
            data={historicalFigures}
            renderItem={renderFigureItem}
            keyExtractor={keyExtractor}
            contentContainerStyle={styles.figureList}
            numColumns={numColumns}
            key={numColumns.toString()}
            showsVerticalScrollIndicator={false}
          />
        )}
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  avatar: {
    borderRadius: 30,
    height: 60,
    width: 60,
    alignSelf: 'center',
    marginBottom: 10,
  },
  container: {
    flex: 1,
    paddingHorizontal: 10,
  },
  figureDescription: {
    fontFamily: 'Poppins_400Regular',
    fontSize: 12,
    marginTop: 4,
    textAlign: 'center',
  },
  figureInfo: {
    alignItems: 'center',
  },
  figureItem: {
    borderRadius: 12,
    elevation: 3,
    flex: 1,
    margin: 5,
    padding: 10,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
  },
  figureList: {
    paddingVertical: 10,
  },
  figureName: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 14,
    textAlign: 'center',
  },
  header: {
    alignItems: 'center',
    borderBottomWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 15,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  safeArea: {
    flex: 1,
    paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
  },
  settingsButton: {
    padding: 5,
  },
  title: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 24,
  },
});

export default HomeScreen; burada figure bilgilerinden belli şeyler çekiliyor, systemprompt,description vs. aynı zamanda "ai" değeri de çekilsin istiyorum ve uygun şekilde asenkrona vs kaydedilsin ve diğer description systemprompt gibi değerler gibi dieğr sayfalara geçsin istiyorum. firebaseden "ai" de yazan string bilgisi de çekilecek. sonrasında bu iki sayfada uygun kullanımları gerçekleştirilecek. ai değeri örneğin "command-r" yazıyorsa openaiService den yapılan istekte model ismi olarak örneğin "command-r" yazılacak. şayet hiçbir ai bilgisi firebaseden glememişse default olarak model ismine yani ai değerine openai yazılacak.