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 } from '../components/CustomText';
import { LinearGradient } from 'expo-linear-gradient';

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 [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);

  const getTranslation = useCallback(async (text, isWord = true) => {
    setLoading(true);
    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]);

  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('');
      return;
    }

    setSelectedText(text);
    setTranslation('');
    getTranslation(text, isWord);
    
    measureElement(ref, () => {
      setPopoverVisible(true);
    });
  }, [selectedText, popoverVisible, getTranslation, 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>
                );
              })}
              <TouchableOpacity
                ref={sentenceRef}
                style={styles.translateButton}
                onPress={() => handleTextPress(sentence.trim(), sentenceRef, false)}
              >
                <Text style={[
                  styles.translateButtonText, 
                  { 
                    color: theme.textColor,
                    fontFamily: arabicFont 
                  }
                ]}>
                  {' '}[{locale === 'tr' ? 'çevir' : 'translate'}]{' '}
                </Text>
              </TouchableOpacity>
            </React.Fragment>
          );
        })}
      </View>
    );
  }, [sentences, handleTextPress, theme.textColor, arabicFont, locale]);

  const handlePopoverClose = useCallback(() => {
    setPopoverVisible(false);
    setSelectedText('');
  }, []);

  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}
            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" />
                ) : (
                  <Text 
                    style={[
                      styles.tooltipText, 
                      { 
                        color: theme.textColor,
                        fontFamily: arabicFont 
                      }
                    ]}
                  >
                    {translation}
                  </Text>
                )}
              </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,
  },
  translateButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 4,
  },
  translateButtonText: {
    fontSize: 16,
    opacity: 0.6,
  },
  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)'
  },
});

export default RSSReadScreen;

hacı buradaki çevir butonunu kaldırıp onun yerine bu butonu yerleştir bu imgeyi istiyorum             <TouchableOpacity 
              onPress={() => handleSentenceButtonPress(sentences[0].content)}
              style={{
                padding:3,
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Image
                source={require('../../assets/translate2.png')}
                style={{
                  width: fontSize * 1.2,
                  height: fontSize * 1.2,
                }}
              />
            </TouchableOpacity>