import React, { useState, useCallback, useRef } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  Image,
  Text,
  ActivityIndicator,
  TouchableOpacity,
  Dimensions,
  StatusBar,
} from 'react-native';
import Popover, { Rect } from 'react-native-popover-view';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { CustomTextB,CustomTextR } from '../components/CustomText';
import { LinearGradient } from 'expo-linear-gradient';

// Import the translate2.png image
import translateIcon from '../../assets/translate2.png'; // Adjust the path as necessary

// Import translation source logos using require for local assets
const GOOGLE_TRANSLATE_LOGO = require('../../assets/googletranslate.png');
const CHATGPT_LOGO = require('../../assets/chatgpt.png');

// Import translate-google-api
import translate from 'translate-google-api';

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

const RSSReadScreen = ({ route }) => {
  const { item } = route.params;
  const { theme, t, locale, arabicFont, arabicFontBold } = useThemeAndLanguage();
  const [selectedText, setSelectedText] = useState('');
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [translation, setTranslation] = useState('');
  const [translationSource, setTranslationSource] = useState(null); // Tracks translation source
  const [loading, setLoading] = useState(false);
  const [rect, setRect] = useState(new Rect(0, 0, 0, 0));
  const scrollViewRef = useRef(null);
  const measuringInProgress = useRef(false);
  const popoverContentHeight = useRef(0);

  // Existing getTranslation function for words
  const getTranslation = useCallback(async (text, isWord = true) => {
    setLoading(true);
    setTranslationSource('ai'); // Set translation source to AI
    try {
      const systemPrompt = locale === 'tr' 
        ? "Sen bir Arapça-Türkçe çevirmenisin. Sadece çeviriyi ver, başka bir şey yazma. kelimenin birden fazla anlamı varsa onları da yazabilirsin, 1 2 3 şeklinde sıralayarak."
        : "You are an Arabic-English translator. Provide only the translation, nothing else. If the word has multiple meanings, you can list them as 1 2 3.";

      const response = await fetch('https://text.pollinations.ai/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: text }
          ],
          model: "openai",
          seed: -1,
          jsonMode: false
        }),
      });

      const textData = await response.text();
      const cleanedTranslation = textData
        .replace(/^[^a-zA-ZğüşıöçĞÜŞİÖÇ]+/g, '')
        .replace(/["']/g, '')
        .replace(/^\d+\.\s*/gm, '')
        .split('\n')
        .filter(line => line.trim())
        .join(', ');

      setTranslation(cleanedTranslation);
    } catch (error) {
      console.error('Translation error:', error);
      setTranslation(locale === 'tr' ? 'Çeviri alınamadı' : 'Translation failed');
    } finally {
      setLoading(false);
    }
  }, [locale]);

  // New fetchTranslation function for sentences
  const cleanArabicPunctuation = (text) => {
    // Implement a function to clean Arabic punctuation if needed
    // For simplicity, we'll just trim the text here
    return text.trim();
  };

  const fetchTranslation = useCallback(async (text) => {
    setLoading(true);
    setTranslationSource('google'); // Set translation source to Google
    try {
      const cleanedText = cleanArabicPunctuation(text);
      const translateResponse = await translate(cleanedText, { 
        to: locale === 'tr' ? 'tr' : 'en' 
      });
      // Assuming translate-google-api returns an array of translations
      setTranslation(translateResponse[0]);
    } catch (error) {
      console.error('Error fetching translation:', error);
      setTranslation(locale === 'tr' ? 'Çeviri alınamadı' : 'Translation failed');
    } finally {
      setLoading(false);
    }
  }, [locale]);

  const measureElement = useCallback((ref, callback) => {
    if (measuringInProgress.current) return;
    measuringInProgress.current = true;

    const measureAndSetRect = () => {
      ref.current.measure((x, y, width, height, pageX, pageY) => {
        scrollViewRef.current.measure((sx, sy, swidth, sheight, spageX, spageY) => {
          const scrollOffset = scrollViewRef.current._scrollMetrics?.offset || 0;
          const actualY = pageY - spageY + scrollOffset;
          
          const newRect = new Rect(
            pageX,
            actualY,
            width,
            height
          );
          setRect(newRect);
          measuringInProgress.current = false;
          if (callback) callback();
        });
      });
    };

    requestAnimationFrame(measureAndSetRect);
  }, []);

  const handleTextPress = useCallback((text, ref, isWord = true) => {
    if (selectedText === text && popoverVisible) {
      setPopoverVisible(false);
      setSelectedText('');
      setTranslationSource(null);
      return;
    }

    // Set the selected text
    setSelectedText(text);
    
    // Measure the element and show the popover
    measureElement(ref, () => {
      setPopoverVisible(true);
      // Start fetching the translation after showing the popover
      if (isWord) {
        getTranslation(text, isWord);
      } else {
        fetchTranslation(text);
      }
    });
  }, [selectedText, popoverVisible, getTranslation, fetchTranslation, measureElement]);

  const splitIntoSentences = (text) => {
    return text.match(/[^.!?؟،,]+[.!?؟،,]+/g) || [];
  };

  const cleanDescription = item.content.replace(/<[^>]+>/g, '');
  const sentences = splitIntoSentences(cleanDescription);

  const titleRef = useRef(null);

  const renderContent = useCallback(() => {
    return (
      <View style={styles.textWrapper}>
        {sentences.map((sentence, sentenceIndex) => {
          const words = sentence.trim().split(' ');
          const sentenceRef = useRef(null);

          return (
            <React.Fragment key={sentenceIndex}>
              {words.map((word, wordIndex) => {
                const wordRef = useRef(null);
                return (
                  <TouchableOpacity
                    key={`${sentenceIndex}-${wordIndex}`}
                    ref={wordRef}
                    onPress={() => handleTextPress(word, wordRef, true)}
                    style={styles.wordContainer}
                  >
                    <Text style={[
                      styles.word, 
                      { 
                        color: theme.textColor,
                        fontFamily: arabicFont 
                      }
                    ]}>
                      {word}{wordIndex < words.length - 1 ? ' ' : ''}
                    </Text>
                  </TouchableOpacity>
                );
              })}
              {/* Image-Based Translate Button */}
              <TouchableOpacity 
                ref={sentenceRef}
                onPress={() => handleTextPress(sentence.trim(), sentenceRef, false)}
                style={styles.translateButtonImage}
              >
                <Image
                  source={translateIcon}
                  style={styles.translateIcon}
                />
              </TouchableOpacity>
            </React.Fragment>
          );
        })}
      </View>
    );
  }, [sentences, handleTextPress, theme.textColor, arabicFont, translateIcon]);

  const handlePopoverClose = useCallback(() => {
    setPopoverVisible(false);
    setSelectedText('');
    setTranslationSource(null); // Reset translation source
  }, []);

  return (
    <View style={styles.container}>
      <StatusBar translucent backgroundColor="transparent" />
      <ScrollView
        ref={scrollViewRef}
        style={[styles.scrollView, { backgroundColor: theme.backgroundColor }]}
        scrollEventThrottle={16}
        onScroll={() => {
          if (popoverVisible) {
            handlePopoverClose();
          }
        }}
      >
        {item.thumbnail && (
          <View style={styles.coverContainer}>
            <Image
              source={{ uri: item.thumbnail }}
              style={styles.coverImage}
              resizeMode="cover"
            />
            <LinearGradient
              colors={['transparent', theme.backgroundColor]}
              style={styles.gradient}
              start={{ x: 0, y: 0 }}
              end={{ x: 0, y: 1 }}
            />
          </View>
        )}

        <View style={[
          styles.contentContainer, 
          { 
            marginTop: item.thumbnail ? -60 : 0,
            backgroundColor: theme.backgroundColor 
          }
        ]}>
          <TouchableOpacity
            ref={titleRef}
            onPress={() => handleTextPress(item.title, titleRef, false)}
          >
            <CustomTextB 
              style={[
                styles.title, 
                { 
                  color: theme.textColor,
                  fontFamily: arabicFontBold 
                }
              ]}
            >
              {item.title}
            </CustomTextB>
            {item.source && (
              <Text 
                style={[
                  styles.sourceLabel, 
                  { 
                    color: theme.textColor,
                    fontFamily: arabicFont 
                  }
                ]}
              >
                {locale === 'tr' ? 'Kaynak: ' : 'Source: '}{item.source}
              </Text>
            )}
          </TouchableOpacity>

          <View style={[styles.divider, { backgroundColor: theme.borderColor }]} />

          <View style={styles.textContainer}>
            {renderContent()}
          </View>

          <Popover
            isVisible={popoverVisible}
            onRequestClose={handlePopoverClose}
            from={rect}
            popoverStyle={[
              styles.popover,
              { backgroundColor: theme.backgroundColor }
            ]}
            placement="top"
            arrowSize={{ width: 16, height: 8 }}
            arrowStyle={{ backgroundColor: theme.backgroundColor }}
            backgroundStyle={styles.popoverBackground}
            offset={-60}
            // Remove animation by setting duration and delay to 0
            animationConfig={{
              duration: 0,
              delay: 0,
              useNativeDriver: true
            }}
          >
            <View 
              style={styles.popoverContent}
              onLayout={(event) => {
                const { height } = event.nativeEvent.layout;
                if (height !== popoverContentHeight.current) {
                  popoverContentHeight.current = height;
                }
              }}
            >
              <View style={styles.popoverContentWrapper}>
                {loading ? (
                  <ActivityIndicator color={theme.primaryColor} size="small" />
                ) : (
                  <>
                    <CustomTextR 
                      style={[
                        styles.tooltipText, 
                        { 
                          color: theme.textColor,
                          fontFamily: arabicFont 
                        }
                      ]}
                    >
                      {translation || (locale === 'tr' ? 'Çeviriliyor...' : 'Translating...')}
                    </CustomTextR>
                    {translationSource && (
                      <View style={styles.translationSourceContainer}>
                        <Image
                          source={translationSource === 'google' ? GOOGLE_TRANSLATE_LOGO : CHATGPT_LOGO}
                          style={styles.translationSourceLogo}
                        />
                        <CustomTextR 
                          style={[
                            styles.translationSourceText, 
                            { 
                              color: theme.textColor,
                              fontFamily: arabicFont 
                            }
                          ]}
                        >
                          {translationSource === 'google' ? t('googleTranslateWarning') : t('chatgpt')}
                        </CustomTextR>
                      </View>
                    )}
                  </>
                )}
              </View>
            </View>
          </Popover>
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  coverContainer: {
    height: SCREEN_HEIGHT * 0.5,
    width: SCREEN_WIDTH,
    position: 'relative',
  },
  coverImage: {
    width: '100%',
    height: '100%',
  },
  gradient: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: 200,
  },
  contentContainer: {
    padding: 20,
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    marginTop: -60,
  },
  title: {
    fontSize: 32,
    marginBottom: 10,
    textAlign: 'right',
    lineHeight: 44,
    textShadowColor: "rgba(0, 0, 0, 0.1)",
    textShadowOffset: { width: 0, height: 2 },
    textShadowRadius: 4,
  },
  sourceLabel: {
    fontSize: 14,
    marginTop: 8,
    opacity: 0.8,
  },
  divider: {
    height: 1,
    marginVertical: 20,
    width: '100%',
  },
  textContainer: {
    marginTop: 16,
  },
  textWrapper: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-end',
  },
  wordContainer: {
    flexDirection: 'row',
  },
  word: {
    fontSize: 20,
    lineHeight: 36,
    letterSpacing: 0.5,
  },
  // Updated translate button styles
  translateButtonImage: {
    padding: 3,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 5, // Adjust as needed
  },
  translateIcon: {
    width: 24, // Adjust size as needed
    height: 24,
    resizeMode: 'contain',
  },
  popover: {
    borderRadius: 12,
    padding: 0,
    width: SCREEN_WIDTH * 0.8,
    maxWidth: 300,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.25,
    shadowRadius: 8,
    elevation: 8,
  },
  popoverContent: {
    minHeight: 60,
  },
  popoverContentWrapper: {
    padding: 16,
    alignItems: 'center',
    justifyContent: 'center',
    minHeight: 60,
  },
  tooltipText: {
    fontSize: 16,
    textAlign: 'center',
    lineHeight: 24,
  },
  popoverBackground: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  translationSourceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  translationSourceLogo: {
    width: 20,
    height: 20,
    marginRight: 8,
    resizeMode: 'contain',
  },
  translationSourceText: {
    fontSize: 14,
  },
});

export default RSSReadScreen; hacı burada bir sıkıntı var. bu               <TouchableOpacity 
                ref={sentenceRef}
                onPress={() => handleTextPress(sentence.trim(), sentenceRef, false)}
                style={styles.translateButtonImage}
              >
                <Image
                  source={translateIcon}
                  style={styles.translateIcon}
                />
              </TouchableOpacity> kısım var ya, yanlış cümleleri çeviriyor. metnimiz arapça ona göre yap. şu anda button solundaki cümleyi çeviriyor. kullancıınn gözünden yani henüz bitmemiş olan cümleyi çeviriyor. bunu tersine döndürelim. bir cümle bittiğinde button biten cümleyi çevirsin. başka bir şeyi değiştirme bozma. birde source kısmı daha güzel olabilir. hadi bakalım.