import React, { useRef, useState, useMemo } from 'react';
import { NativeScrollEvent, NativeSyntheticEvent, StyleSheet, View } from 'react-native';
import { Calendar } from 'react-native-calendars';
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 { addExpense } from "../../../services/database";
import { useAuth } from '../../contexts/AuthContext';
import { useRouter } from "expo-router";
import { SimpleDate } from '../../../util/SimpleDate';
import { useTheme } from '../../contexts/ThemeContext';


interface MarkingProps {
    dots?:{color:string, selectedColor?:string, key?:string}[];
} 

type MarkedDates  = {
    [key: string]: MarkingProps;
}

const constructMarkedDates = (data : {[column: string]: any}) => {
    console.log("entered")
    let markedDates: MarkedDates = {};
    data.forEach((value: any) => {
        const dateKey: string = String(value["expense_datetime"]).split(" ")[0]

        if(markedDates[dateKey] === undefined){
            markedDates[dateKey] = {dots: []}
        }
        markedDates[dateKey].dots?.push({color: value["category_color"]})
    })
    return markedDates;
}

export default function Page() {
    const { colors, theme } = useTheme()

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

    const router = useRouter();
    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();

    const expenseDates = useMemo(()=>
        constructMarkedDates(data)
    , [data])
    


    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")}}/>
                    <Calendar key={theme} maxDate={SimpleDate.now().format("YYYY-MM-DD")} style={{margin: 10, borderRadius: 20, padding:10}} theme={{
                        dayTextColor: colors.primaryText,
                        textDisabledColor: colors.secondaryText,
                        todayTextColor: colors.accentColor,
                        calendarBackground: colors.containerColor,
                        arrowColor: colors.accentColor,
                        monthTextColor: colors.accentColor

                    }}
                    markingType='multi-dot'
                    markedDates={expenseDates}
                    >

                    </Calendar>
                    <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> 
    );
}