import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Image,
  TouchableOpacity,
  ActivityIndicator,
  RefreshControl,
} from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { CustomTextR, CustomTextB } from '../components/CustomText';
import useInternetStatus from '../utils/useInternetStatus';
import InternetStatusAlert from '../components/InternetStatusAlert';
import { parseString } from 'react-native-xml2js';

const RSS_URL = 'http://91.107.235.164:5000/feed.xml';
const STORAGE_KEY = '@rss_feed';
const READ_STORIES_KEY = '@readRSSStories';

const RSSTabContent = () => {
  const { theme, t, locale } = useThemeAndLanguage();
  const [rssItems, setRssItems] = useState([]);
  const [sources, setSources] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState(null);
  const [readStories, setReadStories] = useState(new Set());
  const [showInternetAlert, setShowInternetAlert] = useState(false);
  const { isConnected } = useInternetStatus();
  const navigation = useNavigation();
  const [selectedSource, setSelectedSource] = useState('all');

  const loadReadStories = useCallback(async () => {
    try {
      const readStoriesString = await AsyncStorage.getItem(READ_STORIES_KEY);
      if (readStoriesString) {
        setReadStories(new Set(JSON.parse(readStoriesString)));
      }
    } catch (err) {
      console.error('Error loading read RSS stories:', err);
    }
  }, []);

  useEffect(() => {
    loadReadStories();
  }, [loadReadStories]);

  const markStoryAsRead = useCallback(async (storyId) => {
    try {
      const newReadStories = new Set(readStories);
      newReadStories.add(storyId);
      setReadStories(newReadStories);
      await AsyncStorage.setItem(READ_STORIES_KEY, JSON.stringify(Array.from(newReadStories)));
    } catch (err) {
      console.error('Error saving read RSS story:', err);
    }
  }, [readStories]);

  const handleStoryPress = useCallback((item) => {
    markStoryAsRead(item.link);
    navigation.navigate('RSSReadScreen', { item });
  }, [navigation, markStoryAsRead]);

  const parseRSSItem = (item) => {
    try {
      return {
        title: item.title?.[0] || '',
        link: item.link?.[0] || '',
        content: item.content?.[0] || '',
        thumbnail: item.thumbnail?.[0] || '',
        source: item.source?.[0] || '',
        pubDate: item.pubDate?.[0] ? new Date(item.pubDate[0]) : new Date()
      };
    } catch (error) {
      console.warn('Error parsing RSS item:', error);
      return {
        title: '',
        link: '',
        content: '',
        thumbnail: '',
        source: '',
        pubDate: new Date()
      };
    }
  };

  const fetchRSS = async () => {
    try {
      if (!isConnected) {
        setShowInternetAlert(true);
        setLoading(false);
        return;
      }

      const response = await fetch(RSS_URL);
      const responseData = await response.text();

      parseString(responseData, (err, result) => {
        if (err) {
          throw err;
        }

        if (result && result.rss && result.rss.channel && result.rss.channel[0].item) {
          const items = result.rss.channel[0].item.map(parseRSSItem);
          setRssItems(items);
          
          const uniqueSources = Array.from(
            new Set(items.map(item => item.source))
          ).filter(Boolean).sort();
          
          setSources(uniqueSources);
        }
      });

      setLoading(false);
    } catch (err) {
      console.error('Error fetching or parsing RSS feed:', err);
      setError(err);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRSS();
  }, [isConnected]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await fetchRSS();
    setRefreshing(false);
  }, []);

  const formatTimeAgo = useCallback((date) => {
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);

    if (diffInSeconds < 60) return t('justNow');
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} ${t('minutesAgo')}`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} ${t('hoursAgo')}`;
    if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} ${t('daysAgo')}`;
    if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} ${t('monthsAgo')}`;
    return `${Math.floor(diffInSeconds / 31536000)} ${t('yearsAgo')}`;
  }, [t]);

  const renderRSSItem = useCallback(({ item }) => {
    const isRead = readStories.has(item.link);

    return (
      <TouchableOpacity 
        style={[styles.itemContainer, { backgroundColor: theme.lighterCardBackgroundColor }]}
        onPress={() => handleStoryPress(item)}
      >
        {item.thumbnail ? (
          <Image 
            source={{ uri: item.thumbnail }}
            style={[styles.thumbnail, isRead && styles.readStoryImage]}
            resizeMode="cover"
          />
        ) : (
          <View style={[styles.thumbnail, styles.noImage]}>
            <Ionicons name="image-outline" size={40} color="gray" />
          </View>
        )}
        <View style={styles.textContainer}>
          <Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: 'NotoSansArabic-Regular' }]}>
            {item.title}
          </Text>
          <CustomTextR style={[styles.description, { color: theme.textColor }]}>
            {item.content ? item.content.substring(0, 100) + '...' : ''}
          </CustomTextR>
          <View style={styles.infoContainer}>
            <CustomTextB style={[styles.infoText, { color: theme.textColor }]}>
              {formatTimeAgo(item.pubDate)}
            </CustomTextB>
            {item.source && (
              <CustomTextR style={[styles.sourceText, { color: theme.textColor }]}>
                {item.source}
              </CustomTextR>
            )}
          </View>
        </View>
      </TouchableOpacity>
    );
  }, [handleStoryPress, theme, readStories, formatTimeAgo]);

  const renderSourceButtons = () => (
    <View style={styles.categoryContainer}>
      <TouchableOpacity
        style={[
          styles.categoryLabel,
          selectedSource === 'all' && styles.selectedCategoryButton,
        ]}
        onPress={() => setSelectedSource('all')}
      >
        <CustomTextB style={[
          styles.categoryText,
          { color: selectedSource === 'all' ? theme.primaryColor : theme.textColor }
        ]}>
          {t('allSources')}
        </CustomTextB>
      </TouchableOpacity>
      {sources.map(source => (
        <TouchableOpacity
          key={source}
          style={[
            styles.categoryLabel,
            selectedSource === source && styles.selectedCategoryButton,
          ]}
          onPress={() => setSelectedSource(source)}
        >
          <CustomTextB style={[
            styles.categoryText,
            { color: selectedSource === source ? theme.primaryColor : theme.textColor }
          ]}>
            {source}
          </CustomTextB>
        </TouchableOpacity>
      ))}
    </View>
  );

  const getFilteredItems = () => {
    if (selectedSource === 'all') {
      return rssItems;
    }
    return rssItems.filter(item => item.source === selectedSource);
  };

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

  return (
    <View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      <InternetStatusAlert
        visible={showInternetAlert}
        onDismiss={() => setShowInternetAlert(false)}
      />
      <FlatList
        ListHeaderComponent={renderSourceButtons}
        data={getFilteredItems()}
        renderItem={renderRSSItem}
        keyExtractor={item => item.link}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={[theme.primaryColor]}
          />
        }
        initialNumToRender={5}
        maxToRenderPerBatch={5}
        windowSize={11}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  itemContainer: {
    flexDirection: 'row',
    margin: 10,
    borderRadius: 12,
    overflow: 'hidden',
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 3,
  },
  thumbnail: {
    width: 120,
    height: 120,
  },
  noImage: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
  },
  readStoryImage: {
    opacity: 0.5,
  },
  textContainer: {
    flex: 1,
    padding: 12,
    justifyContent: 'space-between',
  },
  titleArabic: {
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'right',
    marginBottom: 6,
  },
  description: {
    fontSize: 13,
    marginTop: 4,
    textAlign: 'right',
    lineHeight: 18,
  },
  infoContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 8,
  },
  infoText: {
    fontSize: 11,
  },
  categoryContainer: {
    paddingTop:20,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    marginVertical: 5,
  },
  categoryLabel: {
    backgroundColor: 'white',
    borderRadius: 7,
    paddingVertical: 2,
    paddingHorizontal: 2,
    marginHorizontal: 3,
    marginBottom: 5,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  categoryText: {
    fontSize: 11,
    padding: 6,
    textTransform: 'uppercase',
  },
  sourceText: {
    fontSize: 11,
    textAlign: 'right',
  },
});

export default RSSTabContent; BU KODDA BELLİ DEĞİŞİKLİKLER YAPACAKSIN. İŞTE YAPACAĞIN DEĞİŞİKLİK KODLARI: SONRASINDA EKSİKSİZ BANA AT:

import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Image,
  TouchableOpacity,
  ActivityIndicator,
  RefreshControl,
} from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { CustomTextR, CustomTextB } from '../components/CustomText';
import useInternetStatus from '../utils/useInternetStatus';
import InternetStatusAlert from '../components/InternetStatusAlert';
import { parseString } from 'react-native-xml2js';

const RSS_URL = 'http://91.107.235.164:5000/feed.xml';
const STORAGE_KEY = '@rss_feed';
const READ_STORIES_KEY = '@readRSSStories';

const RSSTabContent = () => {
  const { theme, t, locale, arabicFont, arabicFontBold } = useThemeAndLanguage();
  const [rssItems, setRssItems] = useState([]);
  const [sources, setSources] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState(null);
  const [readStories, setReadStories] = useState(new Set());
  const [showInternetAlert, setShowInternetAlert] = useState(false);
  const { isConnected } = useInternetStatus();
  const navigation = useNavigation();
  const [selectedSource, setSelectedSource] = useState('all');

  // ... [previous code remains the same until renderRSSItem]

  const renderRSSItem = useCallback(({ item }) => {
    const isRead = readStories.has(item.link);

    return (
      <TouchableOpacity 
        style={[styles.itemContainer, { backgroundColor: theme.lighterCardBackgroundColor }]}
        onPress={() => handleStoryPress(item)}
      >
        {item.thumbnail ? (
          <Image 
            source={{ uri: item.thumbnail }}
            style={[styles.thumbnail, isRead && styles.readStoryImage]}
            resizeMode="cover"
          />
        ) : (
          <View style={[styles.thumbnail, styles.noImage]}>
            <Ionicons name="image-outline" size={40} color="gray" />
          </View>
        )}
        <View style={styles.textContainer}>
          <Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: arabicFont }]}>
            {item.title}
          </Text>
          <CustomTextR style={[styles.description, { color: theme.textColor, fontFamily: arabicFont }]}>
            {item.content ? item.content.substring(0, 100) + '...' : ''}
          </CustomTextR>
          <View style={styles.infoContainer}>
            <View style={[styles.badge, { backgroundColor: theme.primaryColor }]}>
              <CustomTextB style={[styles.infoText, { color: 'white' }]}>
                {formatTimeAgo(item.pubDate)}
              </CustomTextB>
            </View>
            {item.source && (
              <View style={[styles.badge, { backgroundColor: theme.lighterCardBackgroundColor }]}>
                <CustomTextR style={[styles.sourceText, { color: theme.textColor }]}>
                  {item.source}
                </CustomTextR>
              </View>
            )}
          </View>
        </View>
      </TouchableOpacity>
    );
  }, [handleStoryPress, theme, readStories, formatTimeAgo, arabicFont]);

  // ... [rest of the code remains the same]

  return (
    <View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      <InternetStatusAlert
        visible={showInternetAlert}
        onDismiss={() => setShowInternetAlert(false)}
      />
      <FlatList
        ListHeaderComponent={renderSourceButtons}
        data={getFilteredItems()}
        renderItem={renderRSSItem}
        keyExtractor={item => item.link}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={[theme.primaryColor]}
          />
        }
        initialNumToRender={5}
        maxToRenderPerBatch={5}
        windowSize={11}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  // ... [previous styles remain the same]
  titleArabic: {
    fontSize: 22, // Increased from 16
    fontWeight: 'bold',
    textAlign: 'right',
    marginBottom: 6,
  },
  description: {
    fontSize: 20, // Increased from 13
    marginTop: 4,
    textAlign: 'right',
    lineHeight: 26, // Adjusted line height for better readability
  },
  badge: {
    borderRadius: 15,
    paddingVertical: 4,
    paddingHorizontal: 8,
    marginHorizontal: 2,
  },
  infoContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 8,
  },
  infoText: {
    fontSize: 11,
    color: 'white',
  },
  sourceText: {
    fontSize: 11,
    textAlign: 'right',
  },
  // ... [rest of the styles remain the same]
});

export default RSSTabContent;