// RSSReadScreen.js
import React, { useCallback, useRef, useState, useMemo } from 'react';
import {
  ActivityIndicator,
  Dimensions,
  Image,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Linking,
} from 'react-native';
import Popover, { Rect } from 'react-native-popover-view';
import { CustomTextB, CustomTextR } from '../components/CustomText';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { LinearGradient } from 'expo-linear-gradient';
import { BottomSheetModal, BottomSheetModalProvider, BottomSheetScrollView } from '@gorhom/bottom-sheet';
import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import translate from 'translate-google-api';
import FontSettings from '../components/FontSettings';

// Import the translate2.png image
import translateIcon from '../../assets/translate2.png';

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

const ARABIC_FONTS = {
  'Mirza': require('../../assets/fonts/mirza.ttf'),
  'NotoSansArabic': require('../../assets/fonts/NotoSansArabic-Regular.ttf'),
  'Amiri': require('../../assets/fonts/amiri.ttf'),
  'NotoNaskhArabic': require('../../assets/fonts/noto.ttf'),
};

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

const RSSReadScreen = ({ route }) => {
  const { item } = route.params;
  const { theme, t, locale, arabicFont, arabicFontBold, setFontFamily } = useThemeAndLanguage();
  const [selectedText, setSelectedText] = useState('');
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [translation, setTranslation] = useState('');
  const [translationSource, setTranslationSource] = useState(null);
  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 titleRef = useRef(null);

  // Font Controls State
  const [fontSize, setFontSize] = useState(22);
  const settingsBottomSheetModalRef = useRef(null);

  // Source link handler
  const handleSourcePress = useCallback(() => {
    if (item.link) {
      Linking.openURL(item.link);
    }
  }, [item.link]);

  // Existing getTranslation function for words
  const getTranslation = useCallback(async (text, isWord = true) => {
    setLoading(true);
    setTranslationSource('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]);

  // Clean Arabic punctuation
  const cleanArabicPunctuation = (text) => {
    return text.trim();
  };

  // Fetch translation for sentences
  const fetchTranslation = useCallback(async (text) => {
    setLoading(true);
    setTranslationSource('google');
    try {
      const cleanedText = cleanArabicPunctuation(text);
      const translateResponse = await translate(cleanedText, { 
        to: locale === 'tr' ? 'tr' : 'en' 
      });
      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;
    }

    setSelectedText(text);
    
    measureElement(ref, () => {
      setPopoverVisible(true);
      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 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,
                        fontSize: fontSize,
                      }
                    ]}>
                      {word}{wordIndex < words.length - 1 ? ' ' : ''}
                    </Text>
                  </TouchableOpacity>
                );
              })}
              <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, fontSize]);

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

  // Font Controls Functions
  const increaseFontSize = useCallback(() => setFontSize(prevSize => prevSize + 2), []);
  const decreaseFontSize = useCallback(() => setFontSize(prevSize => prevSize - 2), []);

  const openSettingsModal = useCallback(() => {
    settingsBottomSheetModalRef.current?.present();
  }, []);

  return (
    <BottomSheetModalProvider>
      <View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
        <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,
                    fontSize: fontSize + 6,
                    fontFamily: arabicFontBold,
                  }
                ]}
              >
                {item.title}
              </CustomTextB>
            </TouchableOpacity>

            {item.source && (
              <TouchableOpacity 
  onPress={handleSourcePress}
  style={[
    styles.sourceButton, 
    { 
      backgroundColor: 'transparent', 
      borderColor: theme.primaryColor, 
      borderWidth: 1 
    }
  ]}
>
  <CustomTextR
    style={[
      styles.sourceButtonText, 
      { color: theme.primaryColor }
    ]}
  >
    {t('goTo')}: {item.source}
  </CustomTextR>
</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" />
                  ) : (
                    <>
                      <CustomTextR 
                        style={[
                          styles.tooltipText, 
                          { 
                            color: theme.textColor,
                          }
                        ]}
                      >
                        {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,
                              }
                            ]}
                          >
                            {translationSource === 'google' ? t('googleTranslateWarning') : t('chatgpt')}
                          </CustomTextR>
                        </View>
                      )}
                    </>
                  )}
                </View>
              </View>
            </Popover>
          </View>
        </ScrollView>

        <TouchableOpacity
          style={styles.settingsButton}
          onPress={openSettingsModal}
        >
          <Ionicons name="text" size={24} color={theme.textColor} />
        </TouchableOpacity>

        <BottomSheetModal
          ref={settingsBottomSheetModalRef}
          index={0}
          snapPoints={['85%']}
          handleStyle={{ backgroundColor: theme.backgroundColor }}
          backgroundStyle={{ backgroundColor: theme.backgroundColor }}
        >
          <BottomSheetScrollView contentContainerStyle={styles.settingsContent}>
            <FontSettings
              fontSize={fontSize}
              increaseFontSize={increaseFontSize}
              decreaseFontSize={decreaseFontSize}
              setFontFamily={setFontFamily}
              currentFontFamily={arabicFont}
              theme={theme}
              t={t}
            />
          </BottomSheetScrollView>
        </BottomSheetModal>
      </View>
    </BottomSheetModalProvider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  knownWord: {
    backgroundColor: 'rgba(0, 255, 0, 0.1)',
    borderRadius: 10,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  thumbnail: {
    width: '100%',
    aspectRatio: 1/1,
  },
  content: {
    padding: 5,
  },
  header: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop:20,
  },
  titleArabic: {
    fontSize: 32,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 10,
  },
  fontSizeControl: {
    marginHorizontal: 5,
  },

  paragraphContainer: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: 10,
  },

  descriptionArabic: {
    padding: 3,
    textAlign: 'justify',
  },
  selectedSentence: {
    backgroundColor: 'rgba(255, 215, 0, 0.3)',
  },
  settingsContent: {
    flexGrow: 1,
    padding: 20,
  },
  exampleCard: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 15,
    marginVertical: 20,
    width: '90%',
    alignSelf: 'center',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  exampleText: {
    textAlign: 'center',
  },
  fontSizeControls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
    marginBottom: 20,
  },
  fontSizeButton: {
    alignItems: 'center',
  },
  fontSizeButtonText: {
    marginTop: 5,
    fontSize: 12,
    color: 'gray',
    textAlign: 'center',
  },
  fontOptionsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    width: '100%',
    alignSelf: 'center',
  },
  fontOption: {
    width: '45%',
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 10,
    marginBottom: 20,
    alignItems: 'center',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
  },
  fontOptionText: {
    fontSize: 16,
    marginBottom: 5,
    textAlign: 'center',
  },
  fontOptionSample: {
    fontSize: 18,
  },
  headerContainer: {
    marginVertical: 10,
    backgroundColor: 'rgba(0, 0, 0, 0.03)',
    borderRightWidth: 5,
    width: '97%',
  },
  subHeaderContainer: {
    marginVertical: 10,
    backgroundColor: 'rgba(0, 0, 0, 0.03)',
    borderRightWidth: 3,
    width: '97%',
  },
  imageStyle: {
    width: "90%",
    alignSelf: "center",
    marginBottom: 10,
    aspectRatio: 1 / 1,
    elevation: 1,
    borderRadius: 15,
  },
  bottomSheetContent: {
    flexGrow: 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,
    paddingHorizontal: 25,

  },
  sourceButton: {
    marginTop: 8,
    paddingHorizontal: 10, // Daha dar hale getirdik
    paddingVertical: 6, // Dikeyde de küçülttük
    borderRadius: 8, // Kenarları yuvarlattık
    alignSelf: 'flex-center', // Sağ tarafa sabitledik
    borderWidth: 1, // Kenarlık boyutu
    backgroundColor: 'transparent', // Şeffaf arkaplan
  },
  sourceButtonText: {
    fontSize: 12, // Yazı boyutunu küçülttük
    fontWeight: 'bold', // Yazıyı belirgin yaptık
    textAlign: 'center', // Ortaladık
  },
  divider: {
    height: 1,
    marginVertical: 20,
    width: '100%',
  },
  textContainer: {
    marginTop: 16,
    
  },
  textWrapper: {
    flex: 1,
    flexDirection: 'row-reverse', // Align text from right to left
    flexWrap: 'wrap',
    paddingHorizontal: 25,
    justifyContent: 'space-between', // Distribute space equally
    textAlign: 'justify', // Justify text within lines
  },
  wordContainer: {
    flexDirection: 'row',
  },
  word: {
    lineHeight: 36,
    letterSpacing: 0.5,
  },
  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.2)'
  },
  translationSourceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  translationSourceLogo: {
    width: 20,
    height: 20,
    marginRight: 8,
    resizeMode: 'contain',
  },
  translationSourceText: {
    fontSize: 14,
  },
  // Settings Button
  settingsButton: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    backgroundColor: 'transparent', // Can be changed if needed
    borderRadius: 30,
    padding: 10,
    elevation: 5,
  },
});

export default RSSReadScreen; hacı buradaki font seçme butonunu en alta sabitleyelim width yüzde 100 olsun üç nokta olsun. tıklayınca açılsın. şu sağdaki düğme iptal