import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useTheme } from '../../app/contexts/ThemeContext';
import useFetch from '../../hooks/useFetch';
import { CategoryType } from '../../services/database';

const SavingsOverview = () => {
    const { colors } = useTheme();
    const [saved, setSaved] = useState(0);
    const [goal, setGoal] = useState(0);

    const savedQuery = {
        sql: `SELECT SUM(e.amount) as total FROM expense e LEFT JOIN category c ON e.category_guid = c.guid WHERE c.type = '${CategoryType.SAVING.toString()}'`,
        args: []
    };  

    const goalQuery = {
        sql: `SELECT SUM(allocated_amount) as total FROM category WHERE type = '${CategoryType.SAVING.toString()}'`,
        args: []
    };

    const { data: savedData, isLoading: savedLoading } = useFetch(savedQuery);
    const { data: goalData, isLoading: goalLoading } = useFetch(goalQuery);

    useEffect(() => {
        if (savedData) {
            setSaved(savedData[0]?.total || 0);
        }
        if (goalData) {
            setGoal(goalData[0]?.total || 0);
        }
    }, [savedData, goalData]);

    const styles = StyleSheet.create({
        container: {
            margin: 10,
            borderRadius: 5,
            alignItems: 'center',
            justifyContent: 'center'
        },
        text: {
            fontSize: 26,
            color: colors.primaryText
        },
        boldText: {
            fontWeight: 'bold'
        }
    });

    if (savedLoading || goalLoading) {
        return <Text>Loading...</Text>;
    }

    return (
        <View style={styles.container}>
            <Text style={styles.text}>
                You have saved <Text style={styles.boldText}>{saved.toFixed(2)}€</Text> out of your goal of <Text style={styles.boldText}>{goal.toFixed(2)}€</Text>.
            </Text>
        </View>
    );
};

export default SavingsOverview;