import { router, useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { SafeAreaView, StyleSheet, Text, TextInput, View } from "react-native";
import { AutoDecimalInput, CustomColorPicker, NavigationButton, TypeSelectorSwitch } from "../../../components";
import useFetch from "../../../hooks/useFetch";
import { deleteCategory, deleteExpense, updateCategory } from "../../../services/database";
import { useTheme } from "../../contexts/ThemeContext";

const addCategory = () => {
    const {colors} = useTheme();
    const {category_guid, category_amount, category_color, category_name, category_type} = useLocalSearchParams();

    const [categoryName, setCategoryName] = useState(category_name.toString());
    const [categoryColor, setCategoryColor] = useState(category_color.toString());
    const [selectedType, setSelectedType] = useState(category_type.toString());
    const [amount, setAmount] = useState(Number.parseFloat(category_amount.toString()));

    const {data} = useFetch({sql: "SELECT * FROM expense WHERE category_guid = ?", args: [category_guid.toString()]});

    return (
        <SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: colors.backgroundColor}]}>
            <Text style={[styles.headingTextStyle, {color: colors.primaryText}]}>Edit Category</Text>
            
            <View style={[styles.containerStyle, {backgroundColor: colors.containerColor}]}>
                <View style={[styles.textInputViewStyle, {backgroundColor: colors.elementDefaultColor}]}>
                    <TextInput placeholder={"Enter Category Name..."} value={categoryName} placeholderTextColor={colors.secondaryText} style={[styles.textInputStyle, {color: colors.primaryText}]} onChangeText={(newName: string) => {
                        setCategoryName(newName);
                    }}/>
                </View>

                <View style={styles.budgetInput}>
                    <AutoDecimalInput label={"Allocated:"} onValueChange={(value) => {
                        setAmount(!Number.isNaN(Number.parseFloat(value)) ? Number.parseFloat(value) : 0);
                    }}/>  
                </View>

                <TypeSelectorSwitch 
                currentSelected={selectedType}
                handleButtonPress={(type) => {
                    setSelectedType(type);
                }}
                />

                <View>
                   <CustomColorPicker color={categoryColor} handleColorChange={(color) => {
                        setCategoryColor(color);
                    }}/> 
                </View>

                <View style={styles.deleteButtonView}>
                    <NavigationButton text={"Delete Cateogry"} onPress={() => {
                        for (let i = 0; i < data.length;) {
                            deleteExpense(data[i].guid).then(() => {
                                i++
                            });
                        } 
                        deleteCategory(category_guid.toString()).then(() => {
                           router.push("/(tabs)/(budget)"); 
                        }); 
                    }}/>
                </View>

                <View style={styles.navigationButtonViewStyle}>
                    <NavigationButton text="Back" onPress={() => {
                        router.back();
                    }}/>
                    <NavigationButton text="Save" onPress={() => {
                        updateCategory(category_guid.toString(), categoryName, categoryColor, selectedType, amount).then(() => {
                            router.back();
                        });
                    }}/> 
                </View>
            </View>
        </SafeAreaView>
    );
}

export default addCategory;

const styles = StyleSheet.create({
    deleteButtonView: {

    },
    containerStyle: {
        flex: 1,
        margin: 10,
        borderRadius: 10,
    },
    safeAreaViewStyle: {
        flex: 1,
        flexDirection: "column" 
    },
    headingTextStyle: {
        fontSize: 40,
        fontWeight: "bold",
        alignSelf: "center",
        marginVertical: 10,
    },
    navigationButtonViewStyle: {
        flexDirection: "row",
        justifyContent: "center",
        marginBottom: 10,
    },
    textInputViewStyle: {
        borderRadius: 10,
        paddingVertical: 10,
        margin: 10,
    },
    textInputStyle: {
        paddingHorizontal: 10,
        fontSize: 25,
    },
    budgetInput: {
        marginBottom: 10,
        marginHorizontal: 10,
    }
});