import AsyncStorage from '@react-native-async-storage/async-storage';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import { SafeAreaView } from 'react-native-safe-area-context';
import { BudgetHeader, LoadingSymbol } from '../../../components';
import CategoryItem from '../../../components/budget/categoryItem';
import useFetch from '../../../hooks/useFetch';
import { useThemeColor } from '../../../hooks/useThemeColor';

export default function Page() {
    const containerColor = useThemeColor("containerColor");

    const [selectedPage, setSelectedPage] = useState("noPageLoaded");

    useEffect(() => {
        AsyncStorage.getItem("currentBudgetPage").then((page) => {
            if(page === "expenses" || page === "savings") {
                setSelectedPage(page);
            }
        }).catch((error) => {
            console.log("Error fetching previous page from Async Storage:", error);
        })
    }, []);

    const {data, isLoading, reFetch} = useFetch({sql: "SELECT guid as category_guid, name as category_name, color as category_color FROM category WHERE type = ?", args: selectedPage === "expenses" ? ["expense"] : selectedPage === "savings" ? ["saving"] : []});

    useEffect(() => {
        reFetch();
    }, [selectedPage]);

    const handlePageSelection = (page: string) => {
        setSelectedPage(page);
        AsyncStorage.setItem("currentBudgetPage", page);
    };

    return (
        <SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: containerColor}]}>
            <BudgetHeader selectedPage={selectedPage} handlePageSelection={handlePageSelection}/>
            {isLoading ? (<LoadingSymbol/>) : (
               <FlatList 
                data={data} 
                renderItem = {({item}) => <CategoryItem category={item.category_name} allocated_account={100} color={item.category_color}/>}
                keyExtractor={item => item.category_guid}
                ItemSeparatorComponent={() => {
                    return (<View style={styles.itemSeperatorStyle}/>);
                }}
                /> 
            )}
            {/* <LoadingSymbol/> */}
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    safeAreaViewStyle: {
        flex: 1,
    },
    itemSeperatorStyle: {
        marginVertical: 5,
    },
});