import AsyncStorage from '@react-native-async-storage/async-storage';
import { router } from 'expo-router';
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, Plus } from '../../../components';
import CategoryItem from '../../../components/budget/categoryItem';
import useFetch from '../../../hooks/useFetch';
import { useTheme } from '../../contexts/ThemeContext';

export default function Page() {
    const {colors} = useTheme()
    const containerColor = colors.backgroundColor;

    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 c.guid AS category_guid, c.name AS category_name, c.color AS category_color, c.type AS category_type, SUM(e.amount) as total_expenses, c.allocated_amount as allocated_amount FROM expense e RIGHT JOIN category c ON e.category_guid = c.guid WHERE c.type = ? GROUP BY c.guid", args: selectedPage === "expenses" ? ["expense"] : selectedPage === "savings" ? ["saving"] : []});

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

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

    return (
        <SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: containerColor}]}>
            <BudgetHeader selectedPage={selectedPage} handlePageSelection={handlePageSelection}/>

            <Plus onPress={() => {
                router.push("/(tabs)/budget/addCategory")
            }}/>

            {isLoading ? (<LoadingSymbol/>) : (
               <FlatList 
                data={data} 
                renderItem = {({item}) => <CategoryItem category={item.category_name} allocated_amount={item.allocated_amount ?? 0} color={item.category_color} category_guid={item.category_guid} total_expenses={item.total_expenses ?? 0}/>}
                keyExtractor={item => item.category_guid}
                ItemSeparatorComponent={() => {
                    return (<View style={styles.itemSeperatorStyle}/>);
                }}
                /> 
            )}
        </SafeAreaView>
    );
}

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