import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ActivityIndicator, ScrollView, Dimensions, Alert } from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { db, auth, storage } from '../utils/firebase';
import { collection, query, where, getDoc, getDocs, doc, setDoc, deleteDoc } from 'firebase/firestore';
import { ref, getDownloadURL, uploadBytes } from 'firebase/storage';
import translate from 'translate-google-api';
import { useVocabulary } from '../screens/VocabularyContext';
import Constants from 'expo-constants';
import { Audio } from 'expo-av';
import * as Crypto from 'expo-crypto';
import { Ionicons } from '@expo/vector-icons';


const apiKeyGoogle = Constants.expoConfig?.extra?.apiKeyGoogle || '';
const apiKeyVoiceRSS = Constants.expoConfig?.extra?.apiKeyVoiceRSS || '';
const window = Dimensions.get('window');

const WordExplanationBox = ({ word, onClose, onLayout, storyId }) => {
  const [translation, setTranslation] = useState('');
  const [wordInfo, setWordInfo] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isDetailedInfoLoading, setIsDetailedInfoLoading] = useState(false);
  const [isWordSaved, setIsWordSaved] = useState(false);
  const [sound, setSound] = useState();
  const [isPlayingAudio, setIsPlayingAudio] = useState(false);

  const { locale, t, theme } = useThemeAndLanguage();
  const { updateVocabulary } = useVocabulary();
  const currentUser = auth.currentUser;

  const cleanArabicPunctuation = (text) => {
    if (text.includes(' ')) return text;
    return text.replace(/[،؛؟.:!،".]/g, '').trim();
  };

  const fetchTranslation = useCallback(async () => {
    try {
      const cleanedWord = cleanArabicPunctuation(word);
      const translateResponse = await translate(cleanedWord, { to: locale === 'tr' ? 'tr' : 'en' });
      setTranslation(translateResponse[0]);
    } catch (error) {
      console.error('Error fetching translation:', error);
    } finally {
      setIsLoading(false);
    }
  }, [word, locale]);

  const fetchWordInfo = useCallback(async () => {
    if (word.includes(' ') || /^\d+$/.test(word)) {
      setIsLoading(false);
      return;
    }

    setIsDetailedInfoLoading(true);
    const cleanedWord = cleanArabicPunctuation(word);
    const wordsRef = collection(db, "dictionary");
    const q = query(wordsRef, where("word", "==", cleanedWord));
    
    try {
      const querySnapshot = await getDocs(q);
      if (!querySnapshot.empty) {
        const docData = querySnapshot.docs[0].data();
        setWordInfo(docData);
      } else {
        const aiResponse = await getArabicWordInfo(cleanedWord);
        const parsedResponse = JSON.parse(aiResponse);
        await setDoc(doc(db, "dictionary", cleanedWord), parsedResponse);
        setWordInfo(parsedResponse);
      }
    } catch (error) {
      console.error("Error fetching word info:", error);
    } finally {
      setIsDetailedInfoLoading(false);
    }
  }, [word]);

  const checkUserLoginAndWordStatus = useCallback(async () => {
    if (currentUser && !/^\d+$/.test(word)) {
      const cleanedWord = cleanArabicPunctuation(word);
      const userWordsRef = doc(db, `users/${currentUser.uid}/words/${cleanedWord}`);
      const userWordsSnapshot = await getDoc(userWordsRef);
      setIsWordSaved(userWordsSnapshot.exists());
    } else {
      setIsWordSaved(false);
    }
  }, [currentUser, word]);

  useEffect(() => {
    fetchTranslation();
    if (!/^\d+$/.test(word)) {
      fetchWordInfo();
      checkUserLoginAndWordStatus();
    }
  }, [fetchTranslation, fetchWordInfo, checkUserLoginAndWordStatus, word]);

  const getArabicWordInfo = async (word) => {
    const englishPrompt = `
Provide brief information about an Arabic word in this JSON format. Include the following:
{
  "word": "given word without any changes",
  "root": "arabic root of the word",
  "meaningEN": "[English equivalents]",
  "meaningTR": "[turkish equivalents]",
  "wordTypeEN": "[Noun, verb, adjective, adverb, pronoun, preposition or null (select one of them and write)]",
  "wordTypeTR":"[isim, fiil, sıfat, zarf, zamir ve edat or null (select one of them and write lowercased)]",
  "exampleSentences": [
    {
      "sentence_no": 1,
      "arabic": "first arabic sentence example",
      "english": "English translation of the sentence.",
      "turkish": "Turkish translation of the example sentence."
    },
    ....write 3 senteces max.
  ]
}
The example sentences should reflect Islamic teachings or contexts. But do not use Quran verses and hadiths.
The given word is ${word}. Do not write anything else or the code will be broken.`;

    try {
      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${apiKeyGoogle}`, {
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          contents: [
            {
              parts: [
                {
                  text: englishPrompt
                }
              ]
            }
          ]
        })
      });

      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      const data = await response.json();
      if (data.candidates && data.candidates[0] && data.candidates[0].content && data.candidates[0].content.parts && data.candidates[0].content.parts[0]) {
        return data.candidates[0].content.parts[0].text;
      } else {
        throw new Error('Unexpected response structure');
      }
    } catch (error) {
      console.error('Error fetching AI explanation:', error);
      return 'Failed to fetch AI explanation.';
    }
  };

  const renderWordInfo = () => {
    if (!wordInfo) return null;

    return (
      <View style={[styles.wordInfoContainer, { color: theme.textColor }]}>
        <View style={styles.table}>
          <View style={styles.tableRow}>
            <Text style={[styles.tableHeader, { color: theme.textColor }]}>
              {locale === 'tr' ? 'Kelime' : 'Word'}
            </Text>
            <Text style={[styles.tableContent, styles.arabicText, { color: theme.textColor }]}>
              {wordInfo.word}
            </Text>
          </View>
          <View style={styles.tableRow}>
            <Text style={[styles.tableHeader, { color: theme.textColor }]}>
              {locale === 'tr' ? 'Kök' : 'Root'}
            </Text>
            <Text style={[styles.tableContent, styles.arabicText, { color: theme.textColor }]}>
              {wordInfo.root}
            </Text>
          </View>
          <View style={styles.tableRow}>
            <Text style={[styles.tableHeader, { color: theme.textColor }]}>
              {locale === 'tr' ? 'Anlamı' : 'Meaning'}
            </Text>
            <Text style={[styles.tableContent, styles.alignRight, { color: theme.textColor }]}>
              {locale === 'tr' ? wordInfo.meaningTR.join(', ') : wordInfo.meaningEN.join(', ')}
            </Text>
          </View>
          <View style={styles.tableRow}>
            <Text style={[styles.tableHeader, { color: theme.textColor }]}>
              {locale === 'tr' ? 'Kelime Türü' : 'Word Type'}
            </Text>
            <Text style={[styles.tableContent, styles.alignRight, { color: theme.textColor }]}>
              {locale === 'tr' ? wordInfo.wordTypeTR : wordInfo.wordTypeEN}
            </Text>
          </View>
          <View style={styles.tableRow}>
            <Text style={[styles.tableHeader, styles.exampleTitle, { color: theme.textColor }]}>
              {locale === 'tr' ? 'Örnek Cümleler' : 'Example Sentences'}
            </Text>
          </View>
          {wordInfo.exampleSentences.map((sentence, index) => (
            <View key={index} style={styles.exampleContainer}>
              <Text style={[styles.tableContent, styles.arabicText, { color: theme.textColor }]}>
                {sentence.arabic}
              </Text>
              <Text style={[styles.tableContent, { color: theme.textColor }]}>
                {locale === 'tr' ? sentence.turkish : sentence.english}
              </Text>
            </View>
          ))}
        </View>
        <Text style={styles.warningText}>{t('geminiInfoWarning')}</Text>
      </View>
    );
  };

  const handleAddWord = async () => {
    if (!currentUser) {
      Alert.alert(t('notLoggedIn'), t('loginToAddWord'));
      return;
    }

    if (word.includes(' ') || /^\d+$/.test(word)) {
      Alert.alert(t('cannotAddSentence'), t('onlyWordsCanBeAdded'));
      return;
    }

    const cleanedWord = cleanArabicPunctuation(word);
    const userWordsRef = doc(db, `users/${currentUser.uid}/words/${cleanedWord}`);

    try {
      if (isWordSaved) {
        await deleteDoc(userWordsRef);
        setIsWordSaved(false);
      } else {
        await setDoc(userWordsRef, { date: new Date(), points: 100, storyId: storyId });
        setIsWordSaved(true);
      }

      await updateVocabulary();
    } catch (error) {
      console.error("Error updating user's saved words:", error);
      Alert.alert(t('error'), t('errorUpdatingWords'));
    }
  };

const playSound = async () => {
  const cleanedWord = cleanArabicPunctuation(word);
  const wordHash = await Crypto.digestStringAsync(
    Crypto.CryptoDigestAlgorithm.SHA256,
    cleanedWord
  );
  const audioRef = ref(storage, `sounds/${wordHash}.mp3`);

  try {
    setIsPlayingAudio(true); // Oynatma başladığında durumu true yap

    let audioUrl;
    try {
      audioUrl = await getDownloadURL(audioRef);
    } catch (error) {
      const apiUrl = `https://api.voicerss.org/?key=${apiKeyVoiceRSS}&hl=ar-sa&c=MP3&f=44khz_16bit_stereo&r=-1&src=${encodeURIComponent(cleanedWord)}`;
      const response = await fetch(apiUrl);
      const blob = await response.blob();
      await uploadBytes(audioRef, blob);
      audioUrl = await getDownloadURL(audioRef);
    }

    const { sound: newSound } = await Audio.Sound.createAsync(
      { uri: audioUrl },
      { shouldPlay: true }
    );
    setSound(newSound);

    // Ses çalmaya başladıktan sonra dinle
    newSound.setOnPlaybackStatusUpdate((status) => {
      if (status.didJustFinish) {
        setIsPlayingAudio(false); // Ses bittiğinde durumu false yap
      }
    });
  } catch (error) {
    console.error('Error in playSound function:', error);
    Alert.alert(t('error'), t('errorPlayingAudio'));
  }
};


  useEffect(() => {
    return sound
      ? () => {
          console.log('Unloading Sound');
          sound.unloadAsync();
        }
      : undefined;
  }, [sound]);

  if (isLoading) {
    return (
      <View style={[styles.container, { backgroundColor: theme.backgroundColorForWordBox }]}>
        <ActivityIndicator size="large" color="#81C784" />
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: theme.backgroundColorForWordBox }]} onLayout={onLayout}>
      <ScrollView contentContainerStyle={styles.scrollViewContent}>
        <Text style={[styles.wordText, { color: theme.textColor }]}>{word}</Text>
        <Text style={[styles.translationText, { color: theme.textColor }]}>{translation}</Text>

<TouchableOpacity 
  style={[styles.listenButton, isPlayingAudio && styles.listenButtonDisabled, styles.playButton]} 
  onPress={playSound}
  disabled={isPlayingAudio}
>
  <Text style={styles.listenButtonText}>
    {isPlayingAudio ? (
      <Text style={{ color: theme.primaryColor }}>{t('playing')}</Text>
    ) : (
      <>
        <Ionicons name="play" size={32} color={theme.primaryColor} />
      </>
    )}
  </Text>
</TouchableOpacity>

        <Text style={styles.warningText}>{t('googleTranslateWarning')}</Text>





        {!(/^\d+$/.test(word)) && (
          <>
            {isDetailedInfoLoading ? (
              <>
                <Text style={styles.warningText}>{t('loadingGemini')}</Text>
                <ActivityIndicator size="large" color="#81C784" />
              </>
            ) : (
              <>
                {currentUser && !word.includes(' ') && (
                  <TouchableOpacity 
                    style={[
                      styles.addRemoveButton, 
                      isWordSaved && { backgroundColor: '#FF5252' }
                    ]} 
                    onPress={handleAddWord}
                  >
                    <Text style={styles.addRemoveButtonText}>
                      {isWordSaved ? t('removeWord') : t('addWord')}
                    </Text>
                  </TouchableOpacity>
                )}
                {!currentUser && !word.includes(' ') && (
                  <Text style={styles.warningText}>{t('loginToAddWord')}</Text>
                )}
                {renderWordInfo()}
              </>
            )}
          </>
        )}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  closeButton: {
    alignSelf: 'flex-end',
  },
  scrollViewContent: {
    flexGrow: 1,
    minHeight: window.height,
  },
  wordText: {
    fontSize: 30,
    fontWeight: 'normal',
    textAlign: 'center',
  },
  translationText: {
    fontSize: 20,
    marginVertical: 10,
    textAlign: 'center',
  },
  wordInfoContainer: {
    marginTop: 20,
  },
  table: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 5,
    overflow: 'hidden',
  },
  tableRow: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#ddd',
    paddingVertical: 10,
    paddingHorizontal: 15,
    alignItems: 'center',
  },
  tableHeader: {
    flex: 1,
    fontWeight: 'bold',
  },
  tableContent: {
    flex: 2,
    textAlign: 'center',
  },
  exampleTitle: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  formattedTextContainer: {
    flexDirection: 'row-reverse',
    flexWrap: 'nowrap',
    justifyContent: 'flex-start',
    alignItems: 'right',
  },
  arabicText: {
    fontSize: 24,
    textAlign: 'right',
    writingDirection: 'rtl',
  },
  alignRight: {
    textAlign: 'right',
  },
  exampleContainer: {
    borderBottomWidth: 1,
    borderBottomColor: '#ddd',
    paddingVertical: 10,
    paddingHorizontal: 15,
  },
  warningText: {
    fontSize: 12,
    color: 'gray',
    textAlign: 'center',
    marginTop: 5,
  },
  addRemoveButton: {
    backgroundColor: '#81C784',
    padding: 10,
    borderRadius: 5,
    marginTop: 10,
    alignItems: 'center',
  },
  addRemoveButtonText: {
    color: 'white',
    fontWeight: 'bold',
  },
    listenButtonText: {
    textAlign: 'center', // Metni ortalar
    justifyContent: 'center', // Dikey ortalama
    alignItems: 'center', // Yatay ortalama
    flexDirection: 'row', // Dikey esnek düzen
    // Eğer istersen buraya diğer stilleri de ekleyebilirsin
  },
});

export default WordExplanationBox; burada şöyle bir değişiklik yapacağız:
dictionary/$word olarak kelime bilgilerini çekerken eğer kelimede "image" bilgisi mevcutsa bir kelime bilgilerinin gösterildiği tablonun üstünde birde o resmi thumbnail olarak göstersin:
örneğin:
/dictionary/أَبِيهِ
{
  "detailedword": "<r>هِ</r><b>أَبِي</b>",
  "exampleSentences": [
    {
      "arabic": "رَأَى الْوَلَدُ أَبِيهِ.",
      "english": "The boy saw his father.",
      "sentence_no": 1,
      "turkish": "Çocuk babasını gördü."
    }
  ],
  "image": "https://storage.googleapis.com/readarabic-dec46.appspot.com/dictionaryimages/cb209f626ad0421392cc1da83c384149.jpg",
  "meaningEN": [
    "his father"
  ],
  "meaningTR": [
    "babası"
  ],
  "root": "أَبَو",
  "word": "أَبِيهِ",
  "wordTypeEN": "Noun",
  "wordTypeTR": "isim"
}