import React, { useEffect, useState, useCallback } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  ActivityIndicator, 
  Alert, 
  Dimensions,
  SafeAreaView,
  Platform,
  StatusBar as RNStatusBar
} from 'react-native';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { StatusBar } from 'expo-status-bar';
import CustomText from '../components/CustomText';

interface ChatWithLastMessage extends Chat {
  lastMessage?: string;
  lastMessageTimestamp?: number;
}

const ChatListScreen = () => {
  const navigation = useNavigation();
  const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const isFocused = useIsFocused();

  useEffect(() => {
    const fetchChats = async () => {
      try {
        const chatsData = await AsyncStorage.getItem('chats');
        const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];

        const chatsWithMessages: ChatWithLastMessage[] = await Promise.all(chatsList.map(async (chat) => {
          const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`);
          const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
          const lastMessage = messages[messages.length - 1]?.text || '';
          const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt;
          return { 
            ...chat, 
            lastMessage, 
            lastMessageTimestamp: lastTimestamp 
          };
        }));

        const sortedChats = chatsWithMessages.sort((a, b) => 
          (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
        );

        setChats(sortedChats);
      } catch (error) {
        console.error('Error fetching chats:', error);
        Alert.alert("Hata", "Sohbetler yüklenirken bir hata oluştu.");
      } finally {
        setLoading(false);
      }
    };

    fetchChats();
  }, [isFocused]);

  const deleteChat = useCallback(async (chatId: string) => {
    Alert.alert(
      "Sohbeti Sil",
      "Bu sohbeti silmek istediğinizden emin misiniz?",
      [
        { text: "İptal", style: "cancel" },
        { 
          text: "Sil", 
          style: "destructive",
          onPress: async () => {
            try {
              const updatedChats = chats.filter(chat => chat.id !== chatId);
              await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
              await AsyncStorage.removeItem(`chat_${chatId}_messages`);
              setChats(updatedChats);
            } catch (error) {
              console.error('Error deleting chat:', error);
              Alert.alert("Hata", "Sohbet silinirken bir hata oluştu.");
            }
          }
        }
      ]
    );
  }, [chats]);

  const deleteAllChats = useCallback(async () => {
    Alert.alert(
      "Tüm Sohbetleri Sil",
      `${chats.length} sohbet silinecek. Emin misiniz?`,
      [
        { text: "İptal", style: "cancel" },
        { 
          text: "Sil", 
          style: "destructive",
          onPress: async () => {
            try {
              await AsyncStorage.removeItem('chats');
              for (const chat of chats) {
                await AsyncStorage.removeItem(`chat_${chat.id}_messages`);
              }
              setChats([]);
            } catch (error) {
              console.error('Error deleting all chats:', error);
              Alert.alert("Hata", "Sohbetler silinirken bir hata oluştu.");
            }
          }
        }
      ]
    );
  }, [chats]);

  const renderChatItem = useCallback(({ item }: { item: ChatWithLastMessage }) => (
    <TouchableOpacity
      style={styles.chatItem}
      onPress={() => navigation.navigate('Chat', { chatId: item.id, figure: item.figure })}
    >
      <Image source={{ uri: item.figure.image }} style={styles.avatar} />
      <View style={styles.chatInfo}>
        <CustomText bold style={styles.chatName}>{item.figure.name}</CustomText>
        <CustomText style={styles.chatLastMessage} numberOfLines={1}>
          {item.lastMessage}
        </CustomText>
        <CustomText style={styles.chatDate}>{timeAgo(item.lastMessageTimestamp)}</CustomText>
      </View>
      <TouchableOpacity onPress={() => deleteChat(item.id)} style={styles.deleteButton}>
        <Ionicons name="trash-outline" size={24} />
      </TouchableOpacity>
    </TouchableOpacity>
  ), [deleteChat]);

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

  const timeAgo = (timestamp: number | undefined) => {
    if (!timestamp) return '';
    const now = Date.now();
    const diff = Math.floor((now - timestamp) / 60000);
    if (diff < 1) return `Şimdi`;
    if (diff < 60) return `${diff} dk önce`;
    const hours = Math.floor(diff / 60);
    if (hours < 24) return `${hours} saat önce`;
    const days = Math.floor(hours / 24);
    return `${days} gün önce`;
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar style="dark" />
      <View style={styles.container}>
        <View style={styles.header}>
          <CustomText bold style={styles.title}>Sohbetlerim</CustomText>
          {chats.length > 0 && (
            <TouchableOpacity onPress={deleteAllChats} style={styles.deleteAllButton}>
              <Ionicons name="trash-outline" size={24} color="#FF3B30" />
            </TouchableOpacity>
          )}
        </View>
        {chats.length === 0 ? (
          <View style={styles.emptyContainer}>
            <CustomText style={styles.emptyText}>Hiç sohbetiniz yok! Yeni bir sohbet başlatın.</CustomText>
          </View>
        ) : (
          <FlatList
            data={chats}
            renderItem={renderChatItem}
            keyExtractor={keyExtractor}
            contentContainerStyle={styles.chatList}
          />
        )}
        <TouchableOpacity
          style={styles.fab}
          onPress={() => navigation.navigate('Home')}
        >
          <Ionicons name="add" size={30} color="#fff" />
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

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

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#F8F8F8',
    paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
  },
  container: {
    flex: 1,
    backgroundColor: '#F8F8F8',
    paddingHorizontal: 15,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F8F8F8',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
  },
  title: {
    fontSize: 28,
    color: '#333',
    fontFamily: 'Poppins_400Regular',
  },
  deleteAllButton: {
    padding: 5,
  },
  chatList: {
    paddingTop: 10,
    paddingBottom: 80,
  },
  chatItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    marginBottom: 12,
    marginHorizontal:3,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
        padding: 20,

  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    marginRight: 16,
  },
  chatInfo: {
    flex: 1,
  },
  chatName: {
    fontSize: 18,
    color: '#333',
    fontFamily: 'Poppins_700Bold',
  },
  chatLastMessage: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
    fontFamily: 'Poppins_400Regular',
  },
  chatDate: {
    fontSize: 12,
    color: '#999',
    marginTop: 4,
    fontFamily: 'Poppins_400Regular',
  },
  deleteButton: {
    padding: 8,
  },
  fab: {
    position: 'absolute',
    width: 56,
    height: 56,
    backgroundColor: '#007AFF',
    borderRadius: 28,
    justifyContent: 'center',
    alignItems: 'center',
    right: 16,
    bottom: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 32,
  },
  emptyText: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
    fontFamily: 'Poppins_400Regular',
  },
});

export default ChatListScreen; buraya her girildiğinde mavi loadingler gösteriliyor. bu böyle her girişte yüklenmesin yüklü kalsın hep. aynı zamanda mavi loadingleri kaldır güzel görünmüyor. aynı şeyi burada da yap  // src/screens/HomeScreen.tsx
import React, { useEffect, useState, useCallback } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  ActivityIndicator, 
  Alert,
  SafeAreaView,
  Platform,
  StatusBar as RNStatusBar
} 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';

const HomeScreen = () => {
  const navigation = useNavigation();
  const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchFigures = 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);
      } catch (error) {
        console.error('Error fetching figures:', error);
        Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu.");
      } finally {
        setLoading(false);
      }
    };

    fetchFigures();
  }, []);

  const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
    <TouchableOpacity
      style={styles.figureItem}
      onPress={() => startChat(item)}
    >
      <Image source={{ uri: item.image }} style={styles.avatar} />
      <View style={styles.figureInfo}>
        <CustomText bold style={styles.figureName}>{item.name}</CustomText>
        <CustomText style={styles.figureDescription} numberOfLines={2}>
          {item.description}
        </CustomText>
      </View>
      <Ionicons name="chevron-forward" size={24} color="#007AFF" />
    </TouchableOpacity>
  ), []);

  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 || "Açıklama mevcut değil.",
      isUser: false,
      timestamp: Date.now(),
    };

    try {
      const existingChats = await AsyncStorage.getItem('chats');
      const chats: Chat[] = existingChats ? JSON.parse(existingChats) : [];
      const updatedChats = [...chats, newChat];
      await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));

      const existingMessages = await AsyncStorage.getItem(`chat_${chatId}_messages`);
      const messages: Message[] = existingMessages ? JSON.parse(existingMessages) : [];
      const updatedMessages = [...messages, initialMessage];
      await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));

      navigation.navigate('Chats', { screen: 'Chat', params: { chatId, figure } });
    } catch (error) {
      console.error('Error starting chat:', error);
      Alert.alert("Hata", "Sohbet başlatılırken bir hata oluştu.");
    }
  };

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

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar style="dark" />
      <View style={styles.container}>
        <View style={styles.header}>
          <CustomText bold style={styles.title}>Tarihi Karakterler</CustomText>
          <TouchableOpacity style={styles.infoButton}>
            <Ionicons name="information-circle-outline" size={24} color="#007AFF" />
          </TouchableOpacity>
        </View>
        <FlatList
          data={historicalFigures}
          renderItem={renderFigureItem}
          keyExtractor={keyExtractor}
          contentContainerStyle={styles.figureList}
          showsVerticalScrollIndicator={false}
        />
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
  },
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    paddingHorizontal: 15,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
  },
  title: {
    fontSize: 28,
    color: '#333',
    fontFamily: 'Poppins_700Bold',
  },
  infoButton: {
    padding: 5,
  },
  figureList: {
    paddingTop: 10,
  },
  figureItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    marginBottom: 15,
    padding: 20,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
        marginHorizontal:3,

  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    marginRight: 15,
  },
  figureInfo: {
    flex: 1,
  },
  figureName: {
    fontSize: 18,
    color: '#333',
    fontFamily: 'Poppins_700Bold',
  },
  figureDescription: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
    fontFamily: 'Poppins_400Regular',
  },
});

export default HomeScreen;