import React, { useRef, useState } from 'react';
import { NativeScrollEvent, NativeSyntheticEvent, StyleSheet, View } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ExpenseItem, LoadingSymbol, Plus, SearchBar, Welcome } from '../../../components';
import useFetch from '../../../hooks/useFetch';
import { useThemeColor } from "../../../hooks/useThemeColor";
import { addExpense } from "../../../services/database";
import { useAuth } from '../../contexts/AuthContext';
import { useRouter } from "expo-router";

export default function Page() {

    //Styles
    const styles = StyleSheet.create({
        safeAreaViewStyle: {
            flex: 1, 
            backgroundColor: useThemeColor("backgroundColor")
        },
        container: {
            flex: 1,
            alignItems: "center",
            justifyContent: "center",
        },
        text: {
            color: useThemeColor("primaryText"),
            fontSize: 70,
            fontWeight: "bold"
        },
        loading: {
            color: "red",
        }
    });

    const router = useRouter();
    const {onLogout} = useAuth();
    const [plusShow, setPlusShow] = useState(true);
    const prevOffset = useRef(0);
    

    const profile = require("../../../assets/images/profile.jpg")

    const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>)=>{
        const currentOffset = event.nativeEvent.contentOffset.y >= 0 ? event.nativeEvent.contentOffset.y : 0
        const isScrollingUp : boolean = currentOffset <= prevOffset.current;
        const isTop : boolean = currentOffset === 0
        prevOffset.current = currentOffset
        setPlusShow(isScrollingUp || isTop)
    }

    const newExpense = async (title: string, category_guid: string, date: string, amount: number) => {
        try {
            await addExpense(title, category_guid, date, amount);
        } catch (error: any) {
            console.error("Adding new expense has failed: ", error);
        }
    }

    const {data, isLoading, reFetch} = useFetch();



    return (
        <SafeAreaView edges={["left", "right", "top"]} style={styles.safeAreaViewStyle}>
            {plusShow && <Plus onPress={()=>{
                // router.push("/(tabs)/home/addItem");
                newExpense("Test Title", "3b33b8ac-5fc1-43e5-81fc-cf61628861f7", "69.69.1234", 100).then(() => {
                    reFetch();
                });
            }}/>}

            {isLoading && <LoadingSymbol></LoadingSymbol>}
            
            <FlatList
            data={data}
            ListHeaderComponent={
                <>
                    <Welcome name="My Dude" image={profile} onPress={() => {router.push("/home/userSettings")}}></Welcome>
                    <SearchBar placeholder='Type to Search...'></SearchBar>
                </>
            }
            renderItem = {({item}) => <ExpenseItem category={item.category_name} color={item.category_color} date={item.expense_datetime} title={item.expense_name} value={"10,00$"}/>}
            keyExtractor={item => item.expense_guid}
            ItemSeparatorComponent={()=><View style={{marginVertical: 5}}></View>}
            onScroll={handleScroll}
            scrollEventThrottle={20}
            >
            </FlatList>            
        </SafeAreaView> 
    );
}