import { StyleSheet, Text, View, ScrollView } from 'react-native'
import React, { useEffect } from 'react'
import fonts from '../../../theme/fonts'
import colors from '../../../theme/colors'
import { ToggleButton } from 'react-native-paper'
import SectionHeader from '../Headers/SectionHeader'
import HorizontalNewsCardVariant from '../Cards/HorizontalNewsCardVariant'
import {CATEGORY_URL,ARTICLE_URL, PAGINATE_BY} from '../../../utils/Constants/constants'
import { useConstructor } from '../../../utils/Constants/functions'


// * API Handling

const CategorySection = () => {

    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 fetchCategories = () => {
        
        fetch(
            `http://www.newscout.in/api/v1/menus/?domain=newscout`)
                        .then((res) => res.json())
                        .then((json) => {
                            let categoriesHeading = json.body.results.map((item) => item.heading.name)
                            setCategories(categoriesHeading)
                            setNews({})
                            setNews(categoriesHeading.reduce((result, key) => ({ ...result, [key]: []}), {})),
                            setCategoryValue(categoriesHeading[0])
                            return categoriesHeading
                        }).
                        then((cats) => {
                            cats.forEach(cat=> {
                                fetchNews(cat)
                            });
                            return cats
                        })
                        .catch((err) => console.log(err))
                        .finally(() => console.log("Fetch Categories Executed"))
    }

    

    const fetchNews = (category) => {
        fetch(`http://www.newscout.in/api/v1/article/search/?domain=newscout&category=${category}`)
        .then(res => res.json())
        .then((data) => {
            const newsDataFetch = data.body.results
            const finalNewsData = newsDataFetch.slice(0,PAGINATE_BY).map((article) => ({
                headline: article.title,
                image: {uri:article.cover_image},
                category: article.category,
                root_category: article.root_category,
                timestamp: article.published_on,
                tagline: "Bruh Momento Oi Lorem Ipsum di rubi rabbi",
                id:article.id
            }))
            updateNewsByCategories(category,finalNewsData)
            // categories.forEach((category) => {setNews((prev) => ({...prev,[category]:json.body.results}))})
            return finalNewsData
        })
        .catch((err) => console.log(err))
        .finally(() => console.log("Fetch Category News Executed"))
    }


    useConstructor( () => {
        const cat_data = fetchCategories()
        //console.log(`construct ${categories}`)
        // for (let category in cat_data) {
        //     updateNewsByCategories(category,fetchNews(category))

        // }
    })

    // useEffect(() => {
    //     for (let category in cat_data) {
    //         fetchNews(category)

    //     }
    // })

    return (
        <View style={styles.categoriesContainer}>
            <SectionHeader label={"Categories"} />
            <View style={styles.categoriesPillContainer}>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    <ToggleButton.Group onValueChange={value => { setCategoryValue(value) }}>
                        {
                            categories.map((category) =>
                                <ToggleButton
                                    key={category}
                                    icon={() => <Text style={[category === categoryValue ? styles.selectedPillText : styles.pillText]}>{category}</Text>}
                                    style={[category === categoryValue ? styles.selectedContainer : styles.container, { marginHorizontal: fonts.getSize(4) }]}
                                    value={category}

                                />)
                        }
                    </ToggleButton.Group>
                </ScrollView>
            </View>
            <ScrollView showsVerticalScrollIndicator={false}>
                <View style={styles.categoriesNewsContainer}>
                    <Text>{console.log(news)}</Text>
                    {news[categoryValue] !== undefined 
                        ? news[categoryValue].map((item) =>
                             <HorizontalNewsCardVariant 
                                headline={item.headline}
                                image={item.image}
                                timestamp={item.timestamp}
                                tagline={item.tagline}
                             />)
                        : <Text> News Not Present</Text>
                    }
                </View>
            </ScrollView>
        </View>

    )
}

export default CategorySection

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

    }
})