import { View, Text, StyleSheet, Alert } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import { SIZES } from '../../constants/theme'
import { useTheme } from '../contexts/ThemeContext'
import { AutoDecimalInput, CategorySelector, CategorySelectorModal, DateSelectorButton, RoundedButton, TextInputBar } from '../../components'
import { Category } from '../../types/dbItems'
import DateTimePicker from '@react-native-community/datetimepicker';
import { addExpense, executeQuery } from '../../services/database'
import { SimpleDate } from '../../util/SimpleDate'
import { useLocalSearchParams, useRouter } from 'expo-router'

export default function AddItem() {
  const {colors} = useTheme();
  const router = useRouter();

  const searchParams = useLocalSearchParams()

  const [formatedValue, setFormatedValue] = useState<string>("");
  const [selectorModalVisible, setSelecorModalVisible] = useState<boolean>(false);
  const [selectedCategory, setSelectedCategory] = useState<Category|undefined>()
  const [expenseName, setExpenseName] = useState<string>("");
  const [datePickerShown, setDatePickerShown] = useState<boolean>(false);
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())

  const handleValueChange = (formatedValue: string) => {
    setFormatedValue(formatedValue);
  }

  const handleCategorySelect = (category : Category) => {
    setSelecorModalVisible(false);
    setSelectedCategory(category);
  }

  const validateInput = ():boolean => {
    if(formatedValue == "" || expenseName == "" || selectedCategory === undefined || selectedDate === null){
      return false;
    }
    return true;
  }

  const submit = () => {
    const insert = async () => {
      await addExpense(expenseName, selectedCategory?.guid!, new SimpleDate(selectedDate).format("YYYY-MM-DD"), Number(formatedValue))
    }
    if(validateInput()){
      insert().then(() => {
        router.back();
      })
    }else {
      Alert.alert("Invalid input", "One of the Props is not properly defined")
    }
    
  }

  useEffect(()=>{
    if(searchParams.category !== undefined){
      console.log(searchParams.category)
      executeQuery({sql: "SELECT * FROM category WHERE guid = ?", args: [searchParams.category]}).then((result) =>{
        console.log("then")
        if("rows" in result[0]){
          const category = result[0]["rows"][0];
          setSelectedCategory({name: category["name"], color: category["color"], guid: category["guid"]})
        }
        //setSelectedCategory({name: category["name"], color: category["color"], guid: category["guid"]})
      })
    }
  }, [])
  
  return (
    <View style={styles.container}>
      <CategorySelectorModal visible={selectorModalVisible} onRequestClose={()=>{setSelecorModalVisible(false)}} onCategoryTap={handleCategorySelect}></CategorySelectorModal>
      <AutoDecimalInput onValueChange={handleValueChange} label='Amount'/>
      <CategorySelector onPress={()=>{setSelecorModalVisible(true)}} selectedCategory={selectedCategory}/>
      <TextInputBar placeholder='Name' value={expenseName} onChangeText={(text)=>setExpenseName(text)}/>
      <DateSelectorButton selectedDate={selectedDate} onPress={()=>{setDatePickerShown(true)}}/>
      {datePickerShown &&
        <DateTimePicker 
          value={new Date()}
          maximumDate={new Date()}

          onChange={(event, date)=>{
            setDatePickerShown(false);
            if(date){
              setSelectedDate(date);
            }
          }}
        />}
        <RoundedButton color={colors.accentColor} style={styles.save} onPress={submit}>
          <Text style={[styles.submitText, {color: colors.primaryText}]}>Save</Text>
        </RoundedButton>
    </View>
  )
}

const styles = StyleSheet.create({
  save: {
    marginTop: 40,
    padding: 10,
  },
  container: {
    margin: SIZES.normal,
    display: "flex",
    gap: 10
  }, 
 
  submitText: {
    fontSize: SIZES.large
  }
  
})