import { StyleSheet, Text, View, ScrollView, FlatList } from 'react-native';
import React, { useContext, useEffect } from 'react';
import { ToggleButton } from 'react-native-paper';
import fonts from '../../../constants/fonts';
import colors from '../../../constants/colors';
import HorizontalNewsCardVariant from '../../molecules/Cards/HorizontalNewsCardVariant';
import {
  getScreenType,
  useConstructor,
  navigateToArticle,
  navigateToListViewPage,
  onShare,
} from '../../../constants/functions';
import SectionHeader from '../../molecules/Header/SectionHeader';
import {
  horizontalScale,
  moderateScale,
  verticalScale,
} from '../../../constants/metrics';
import { ThemeContext } from '../../../context/theme.context';
import { getArticlesByCategory, getCategories } from '../../../api/data';
import LoadingScreen from './LoadingScreen';
import { NEWSCOUT_NEWS_URL, PAGINATE_BY } from '../../../api/urls';


const CategorySection = ({ navigation }) => {
  const theme = useContext(ThemeContext);
  const currentTheme = theme.state.theme;

  const [isLoading, setLoading] = React.useState(true);

  const [news, setNews] = React.useState({ all: [] });
  const updateNewsByCategories = (key, value) => {
    setNews(prevObject => ({
      ...prevObject,
      [key]: value,
    }));
  };

  const [categoryValue, setCategoryValue] = React.useState('');
  const [categories, setCategories] = React.useState([]);

  const fetchData = () => {
    getCategories()
      .then(res => {
        let categoryData = res.data.body.results
        setCategories(categoryData);
        setNews(
          categoryData.reduce(
            (result, key) => ({ ...result, [key.heading.name]: [] }),
            {},
          ),
        )

        return categoryData
      }).then(categoryData => {
        categoryData.forEach((category) => fetchNews(category.heading.name))
        return categoryData
      }).then(categoryData => {
        setCategoryValue(categoryData[0].heading.name);
        setLoading(false);
      })
      .catch(err => console.error(`Fetch Categories : ${err}`))
      .finally(() => console.log('Fetch Categories Executed'));
  };

  const fetchNews = category => {
    getArticlesByCategory(category)
      .then(res => {
        console.log(`Fetch News Trial : ${res.data.body.results}`)
        updateNewsByCategories(category, res.data.body.results.slice(0, PAGINATE_BY))
      })
      .catch(err => console.error(`Fetch News : ${err}`))
      .finally(() => console.log('Fetch News Executed'));
  };

  useConstructor(() => {
    fetchData();
  });

  const styles = StyleSheet.create({
    categoriesTitle: {
      flexDirection: 'row',
      paddingTop: verticalScale(20),
      paddingHorizontal: horizontalScale(20),
    },
    categoriesTitleText: {
      flex: 1,
      fontFamily: fonts.type.semibold,
      fontSize: moderateScale(16),
      color: colors().recessive,
    },
    categoriesPillContainer: {
      paddingBottom: verticalScale(8),
      flexDirection: 'row',
      alignItems: 'space-between',
      paddingHorizontal: horizontalScale(16),
      backgroundColor: colors().dominant,
    },
    container: {
      borderRadius: moderateScale(18),
      paddingVertical: verticalScale(8),
      paddingHorizontal: horizontalScale(16),
      backgroundColor: colors().dominant,
      width: 'auto',
    },
    selectedContainer: {
      paddingVertical: verticalScale(8),
      paddingHorizontal: horizontalScale(16),
      backgroundColor: colors().primaryColor,
      borderRadius: moderateScale(18),
      width: 'auto',
    },
    selectedPillText: {
      fontFamily: fonts.type.semibold,
      fontSize: moderateScale(12),
      color: colors().white,
    },
    pillText: {
      fontFamily: fonts.type.semibold,
      fontSize: moderateScale(12),
      color: colors().recessive,
    },
    categoriesNewsContainer: {
      paddingHorizontal: horizontalScale(16),
      paddingTop: verticalScale(10),
      backgroundColor: colors().dominant,
      gap: moderateScale(16),
      flexWrap: 'wrap',
      flexDirection: 'row',

    },
  });

  return (
    <View>
      <SectionHeader label={'Categories'} onPress={() => navigateToListViewPage(navigation, "category", categoryValue)} />
      {isLoading === true ? (
        <LoadingScreen containerHeight={240} />
      ) : (
        <>
          <ScrollView horizontal contentContainerStyle={styles.categoriesPillContainer} showsHorizontalScrollIndicator={false}>
            <ToggleButton.Group
              onValueChange={value => {
                setCategoryValue(value)
              }}>
              {categories.map(category => (
                <ToggleButton
                  key={category.heading.name}
                  icon={() => (
                    <Text
                      style={[
                        category.heading.name === categoryValue
                          ? styles.selectedPillText
                          : styles.pillText,
                      ]}>
                      {category.heading.name}
                    </Text>
                  )}
                  style={[
                    category.heading.name === categoryValue
                      ? styles.selectedContainer
                      : styles.container,
                    { marginHorizontal: horizontalScale(4) },
                  ]}
                  value={category.heading.name}
                />
              ))}
            </ToggleButton.Group>
          </ScrollView>
          <View>
            <ScrollView contentContainerStyle={styles.categoriesNewsContainer} showsVerticalScrollIndicator={false}>

              {news[categoryValue] !== undefined ? 
                <FlatList
                data={news[categoryValue]}
                renderItem={newsObject => 
                  <HorizontalNewsCardVariant
                    headline={newsObject.item.title}
                    image={{ uri: newsObject.item.cover_image }}
                    timestamp={newsObject.item.published_on}
                    tagline={""}
                    onPress={() =>
                      navigateToArticle(navigation, newsObject.item.id, newsObject.item.slug)
                    }
                    onSharePress={() => {
                      onShare({
                        title: "Newscout",
                        message: "Check out unbiased news in Newscout",
                        url: NEWSCOUT_NEWS_URL(newsObject.item.slug),
                      }).catch(err => console.error(err))
                        .finally(() => console.log("Share Link Button"))
                    }}
                  />}

              /> : (
                <LoadingScreen containerHeight={240} />
              )}

            </ScrollView>
          </View>
        </>
      )}
    </View>
  );
};

export default CategorySection;
