import React, { useState, useEffect, useCallback, useRef } from 'react';
import { View, Text, FlatList, StyleSheet, TouchableOpacity, Alert, ActivityIndicator, Animated, Image } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { useVocabulary } from '../screens/VocabularyContext';
import { auth, db } from '../utils/firebase';
import { collection, getDocs, doc, deleteDoc, getDoc } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import LoginScreen from './LoginScreen';
import { CustomTextR, CustomTextB, CustomTextI} from '../components/CustomText'; // CustomText bileşenlerini import edin


const STORAGE_KEY = '@user_words';

const getStoryTitle = async (storyId, locale) => {
  try {
    const storyDocRef = doc(db, 'stories', storyId);
    const storyDoc = await getDoc(storyDocRef);

    if (storyDoc.exists()) {
      const data = storyDoc.data();
      switch (locale) {
        case 'ar':
          return data.storytitlearabic;
        case 'tr':
          return data.storytitleturkish;
        case 'en':
          return data.storytitleenglish;
        default:
          return data.storytitleenglish;
      }
    } else {
      console.error('No such story!');
      return '';
    }
  } catch (error) {
    console.error('Error fetching story title:', error);
    return '';
  }
};

const VocabularyScreen = () => {
  const { theme, t, locale } = useThemeAndLanguage();
  const { vocabulary, updateVocabulary, isLoggedIn } = useVocabulary();
  const [words, setWords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState(null);
  const [expandedWordId, setExpandedWordId] = useState(null);
  const [selectedWordType, setSelectedWordType] = useState('all');

  const fadeAnim = useRef(new Animated.Value(1)).current;
  const navigation = useNavigation();

  const fetchUserWords = useCallback(async () => {
    if (!isLoggedIn) {
      setLoading(false);
      setWords([]);
      return;
    }

    try {
      const cachedWords = await AsyncStorage.getItem(STORAGE_KEY);
      if (cachedWords) {
        setWords(JSON.parse(cachedWords));
      }

      const user = auth.currentUser;
      const wordsCollectionRef = collection(db, 'users', user.uid, 'words');
      const querySnapshot = await getDocs(wordsCollectionRef);
      const userWords = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));

      const detailedWords = await Promise.all(
        userWords.map(async (word) => {
          const wordDocRef = doc(db, 'dictionary', word.id);
          const wordDoc = await getDoc(wordDocRef);
          const wordData = wordDoc.data() || {};

          const exampleSentences = wordData.exampleSentences || [];
          const storyTitle = word.storyId ? await getStoryTitle(word.storyId, locale) : '';

          return { 
            ...word, 
            ...wordData, 
            storyTitle 
          };
        })
      );

      detailedWords.sort((a, b) => {
        const dateA = a.date ? new Date(a.date.seconds * 1000) : new Date(0);
        const dateB = b.date ? new Date(b.date.seconds * 1000) : new Date(0);
        return dateB - dateA;
      });

      await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(detailedWords));
      setWords(detailedWords);
    } catch (err) {
      console.error('Error fetching data:', err);
      setError(err.message);
      setWords([]);
    } finally {
      setLoading(false);
    }
  }, [locale, isLoggedIn]);

  useEffect(() => {
    if (isLoggedIn) {
      fetchUserWords();
    } else {
      setWords([]);
      setLoading(false);
    }
  }, [fetchUserWords, isLoggedIn]);

  useEffect(() => {
    fetchUserWords();
  }, [fetchUserWords, vocabulary]);

  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchUserWords();
    setRefreshing(false);
  };

  const handleDeleteWord = (wordId) => {
    const user = auth.currentUser;
    if (!user) return;

    setWords((prevWords) => {
      const updatedWords = prevWords.filter(w => w.id !== wordId)
        .sort((a, b) => {
          const dateA = a.date ? new Date(a.date.seconds * 1000) : new Date(0);
          const dateB = b.date ? new Date(b.date.seconds * 1000) : new Date(0);
          return dateB - dateA;
        });

      AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(updatedWords))
        .catch(err => console.error('Error updating AsyncStorage:', err));

      deleteDoc(doc(db, 'users', user.uid, 'words', wordId))
        .then(() => {
          console.log('Word deleted from Firestore');
          updateVocabulary();
        })
        .catch((err) => {
          console.error('Error deleting word from Firestore:', err);
        });

      return updatedWords;
    });
  };

  const confirmDeleteWord = (wordId) => {
    Alert.alert(
      t('confirmDelete'),
      t('areYouSure'),
      [
        { text: t('cancel'), style: 'cancel' },
        { text: t('delete'), onPress: () => handleDeleteWord(wordId) },
      ],
      { cancelable: false }
    );
  };

  const toggleExpandWord = (wordId) => {
    setExpandedWordId(expandedWordId === wordId ? null : wordId);
  };

  const renderWordCard = useCallback(({ item }) => {
    const meanings = locale === 'en' ? item.meaningEN : item.meaningTR;
    const wordType = (locale === 'en' ? item.wordTypeEN : item.wordTypeTR).toLowerCase();
    const exampleSentences = item.exampleSentences || [];
    const storyTitle = item.storyTitle;
    const root = item.root;

    return (
      <TouchableOpacity
        style={[styles.wordCard, { backgroundColor: theme.lighterCardBackgroundColor }]}
        onPress={() => toggleExpandWord(item.id)}
        activeOpacity={0.8}
      >
        <View style={styles.wordHeader}>
          {/* Thumbnail Image */}
          {item.image && (
            <Image
              source={item.image ? { uri: item.image } : require('../../assets/placeholder.png')}
              style={styles.thumbnailImage}
              resizeMode="cover"
              accessibilityLabel={`${item.word} thumbnail`}
              onError={(e) => console.error(`Error loading image for ${item.word}:`, e.nativeEvent.error)}
            />
          )}
          <View style={styles.wordContent}>
            <Text style={[styles.wordText, { color: theme.textColor }]}>{item.word}</Text>
            <CustomTextR style={[styles.meaningText, { color: theme.textColor }]}>
              {meanings.join(', ')}
            </CustomTextR>
            <View style={[styles.wordTypeContainer, { flexDirection: 'row' }]}>
              <View style={[styles.rootButton, { backgroundColor: theme.primaryColor + '5' }]}>
                <CustomTextR style={[styles.wordTypeText, { color: theme.textColor }]}>{wordType}</CustomTextR>
              </View>
              <View style={[styles.rootButton, { backgroundColor: theme.primaryColor + '5' }]}>
                <Text style={[styles.wordTypeText, { color: theme.textColor }]}>{root}</Text>
              </View>
            </View>
          </View>
          <View style={styles.iconContainer}>
            <TouchableOpacity
              onPress={() => confirmDeleteWord(item.id)}
              style={[styles.iconButton, { backgroundColor: theme.primaryColor + '20' }]}
            >
              <Ionicons name="trash-outline" size={24} color={theme.textColor} />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => toggleExpandWord(item.id)}
              style={[styles.iconButton, { backgroundColor: theme.primaryColor + '20' }]}
            >
              <Ionicons 
                name={expandedWordId === item.id ? "chevron-up" : "chevron-down"} 
                size={24} 
                color={theme.textColor} 
              />
            </TouchableOpacity>
          </View>
        </View>
        {expandedWordId === item.id && (
          <View style={styles.detailsContainer}>
            {/* Larger Image */}
            {item.image && (
              <View style={styles.largeImageContainer}>
                <Image
                  source={item.image ? { uri: item.image } : require('../../assets/placeholder.png')}
                  style={styles.largeImage}
                  resizeMode="cover"
                  accessibilityLabel={`${item.word} image`}
                  onError={(e) => console.error(`Error loading image for ${item.word}:`, e.nativeEvent.error)}
                />
              </View>
            )}
            <View style={styles.sentencesTable}>
              {exampleSentences.map((sentence, index) => (
                <View key={index} style={styles.sentenceRow}>
                  <Text style={[styles.sentenceText, { color: theme.textColor }]}>{sentence.arabic}</Text>
                  <CustomTextI style={[styles.sentenceTranslation, { color: theme.textColor }]}>
                    {locale === 'en' ? sentence.english : sentence.turkish}
                  </CustomTextI>
                </View>
              ))}
            </View>
            {storyTitle && (
              <TouchableOpacity
                style={styles.storyTitleContainer}
                onPress={() => navigation.navigate('ReadStoryScreen', { storyId: item.storyId })}
              >
                <Text style={[styles.storyTitleText, { color: theme.primaryColor }]}>
                  {storyTitle}
                </Text>
              </TouchableOpacity>
            )}
          </View>
        )}
      </TouchableOpacity>
    );
  }, [theme, locale, t, expandedWordId, navigation]);

  const getWordTypes = () => {
    const types = new Set(words.map(word => locale === 'en' ? word.wordTypeEN : word.wordTypeTR));
    return ['all', ...Array.from(types)];
  };

  const renderWordTypeFilter = () => {
    const wordTypes = getWordTypes();
    return (
      <View style={styles.filterContainer}>
        {wordTypes.map((type) => (
          <TouchableOpacity
            key={type}
            style={[
              styles.filterButton,
              selectedWordType === type && styles.selectedFilterButton,
              { backgroundColor: theme.primaryColor + '20' }
            ]}
            onPress={() => setSelectedWordType(type)}
          >
            <CustomTextB style={[styles.filterButtonText, { color: theme.textColor }]}>
              {type === 'all' ? t('all') : type}
            </CustomTextB>
          </TouchableOpacity>
        ))}
      </View>
    );
  };

  const filteredWords = words.filter(word => 
    selectedWordType === 'all' || 
    (locale === 'en' ? word.wordTypeEN : word.wordTypeTR) === selectedWordType
  );

  if (loading) {
    return (
      <View style={[styles.centerContainer, { backgroundColor: theme.backgroundColor }]}>
        <ActivityIndicator size="large" color={theme.primaryColor} />
      </View>
    );
  }

  if (error) {
    return (
      <View style={[styles.centerContainer, { backgroundColor: theme.backgroundColor }]}>
        <Text style={{ color: theme.dangerColor }}>{t('errorLoading')}: {error}</Text>
      </View>
    );
  }

  if (!isLoggedIn) {
    return (
      <View style={[styles.centerContainer, { backgroundColor: theme.backgroundColor }]}>
        <Ionicons name="cube-outline" size={60} color={theme.textColor} style={styles.icon} />
        <Text style={[styles.message, { color: theme.textColor }]}>
          {t('notLoggedIn')}
        </Text>
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      {renderWordTypeFilter()}
      {filteredWords.length === 0 ? (
        <View style={[styles.centerContainer, { backgroundColor: theme.backgroundColor }]}>
          <Ionicons name="cube-outline" size={60} color={theme.textColor} style={styles.icon} />
          <Text style={[styles.message, { color: theme.textColor }]}>
            {t('noWords')}
          </Text>
        </View>
      ) : (
        <FlatList
          data={filteredWords}
          renderItem={renderWordCard}
          keyExtractor={(item) => item.id}
          refreshing={refreshing}
          onRefresh={handleRefresh}
          contentContainerStyle={{ paddingBottom: 20 }}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  message: {
    fontSize: 18,
    fontWeight: 'bold',
    marginTop: 20,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  wordCard: {
    marginVertical: 5,
    marginHorizontal: 15,
    padding: 15,
    borderRadius: 15,
    elevation: 5,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    marginBottom: 15,
    borderRadius: 10,
    overflow: 'hidden',
    elevation: 3,
    marginHorizontal: 20,
  },
  wordHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  wordContent: {
    flex: 1,
    marginLeft: 10, // Add margin to separate from thumbnail
  },
  wordText: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 5,
    textAlign: 'left',
  },
  meaningText: {
    fontSize: 18,
    marginBottom: 5,
  },
  wordTypeContainer: {
    alignSelf: 'flex-start',
    flexDirection: 'row',  // Arrange word types side by side
  },
  rootButton: {
    marginRight:10,
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 10,
  },
  wordTypeText: {
    fontSize: 14,
    fontWeight: '600',
  },
  iconContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  iconButton: {
    padding: 8,
    borderRadius: 20,
    marginLeft: 10,
  },
  detailsContainer: {
    marginTop: 15,
  },
  sentencesTable: {
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.1)',
    borderRadius: 10,
    overflow: 'hidden',
    marginBottom: 10,
  },
  sentenceRow: {
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0,0,0,0.1)',
  },
  sentenceText: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 5,
  },
  sentenceTranslation: {
    fontSize: 14,
    fontStyle: 'italic',
    textAlign:'center',
  },
  storyTitleContainer: {
    marginTop: 15,
    backgroundColor: 'rgba(0,0,0,0.03)',
    padding: 10,
    borderRadius: 10,
  },
  storyTitleText: {
    fontSize: 16,
    fontWeight: 'normal',
    fontStyle: 'italic',
  },
  filterContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    padding: 10,
  },
  filterButton: {
    padding: 8,
    margin: 5,
    borderRadius: 20,
  },
  selectedFilterButton: {
    backgroundColor: 'rgba(0,0,0,0.2)',
  },
  filterButtonText: {
    fontSize: 14,
    fontWeight: '600',
  },
  // New Styles for Images
  thumbnailImage: {
    width: 50,
    height: 50,
    borderRadius: 5,
  },
  largeImageContainer: {
    alignItems: 'center',
    marginBottom: 15,
  },
  largeImage: {
    width: 150,
    height: 150,
    borderRadius: 10,
  },
});

export default VocabularyScreen; burada bu hatayı alıyorum:

LOG  İnternet durumu güncellendi: Bağlı
 LOG  İnternet durumu güncellendi: Bağlı
 ERROR  No such story!
 ERROR  No such story!
 ERROR  TypeError: meanings.join is not a function (it is undefined)

This error is located at:
    in CellRenderer (created by VirtualizedList)
    in RCTView (created by View)
    in View (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in AndroidSwipeRefreshLayout (created by RefreshControl)
    in RefreshControl (created by VirtualizedList)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
... 198:29 bu hatayı düzelt. no such story hatası kalabilir eğer sayfanın yüklenmesini etkilemiyorsa.