import { useRouter } from "expo-router";
import React, { useEffect, 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, Plus, SearchBar, Welcome } from '../../../components';
import { useThemeColor } from "../../../hooks/hooks";
import { executeQuery } from "../../../services/database";
import { useAuth } from '../../contexts/AuthContext';

export default function Page() {
    const backgroundColor = useThemeColor("backgroundColor")
    const router = useRouter()
    const {onLogout} = useAuth();
    const [plusShow, setPlusShow] = useState(true);
    const prevOffset = useRef(0);
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: "center",
            justifyContent: "center",
        },
        text: {
            color: useThemeColor("primaryText"),
            fontSize: 70,
            fontWeight: "bold"
        }
    });

    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 [data, setData] = useState<{[column: string]: any;}[]>([]);

    useEffect(() => {
        executeQuery("SELECT e.guid AS expense_guid, e.name AS expense_name, c.name AS category_name, e.datetime AS expense_datetime, e.amount AS expense_amount, c.color AS category_color FROM expense e JOIN category c ON e.category_guid = c.guid;").then((result) => {

            if(result === undefined) return;
            setData(result);
        }).catch((error) => {
            throw error;
        });
    }, []);

    return (
        <SafeAreaView style={{flex: 1, backgroundColor: backgroundColor}}>
           {plusShow && <Plus onPress={()=>{
                router.push("/(tabs)/home/addItem")
           }}/>}

            <FlatList
            data={data}
            ListHeaderComponent={
                <>
                    <Welcome name="My Dude" image={profile} onPress={onLogout!}></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>
        
    );
}