import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Keyboard, TouchableWithoutFeedback } from 'react-native';
import InputBox from './components/InputBox';
import ButtonsForm from './components/ButtonsForm';
import SelectForm from './components/SelectForm';
import StyledButton from './components/StyledButton';
import DatePicker from './components/DatePicker';
import moneyApi from './db/postMoney.api';
import { getDateStr } from './utils/dateFunction'

const INIT_ASSETSTYPE = {
    id: 1,
    value: '',
}

const INIT_CATEGORY = {
    id: 1,
    value: '',
}

const INIT_SUBCATEGORY = {
    id: 1,
    value: '',
    foreign_id: 0,
}

const PostMoney = ({ navigation }) => {
    const [selectedIndex, setSelectedIndex] = useState(0)
    const [date, setDate] = useState(getDateStr())
    const [contents, setContents] = useState('')
    const [price, setPrice] = useState('')
    const [asset_type, setAsset_type] = useState([])
    const [selected_asset_type, setSelected_asset_type] = useState(INIT_ASSETSTYPE)
    const [selected_deposit_asset_type, setSelected_deposit_asset_type] = useState(INIT_ASSETSTYPE)
    const [categories, setCategories] = useState([])
    const [selected_cat, setSelected_cat] = useState(INIT_CATEGORY)
    const [subcategories, setSubcategories] = useState([])
    const [selected_subcat, setSelected_subcat] = useState(INIT_SUBCATEGORY)

    
    const [disabled, setDisabled] = useState(true)
    const [success, setSuccess] = useState(false)
    
    useEffect(() => {
        loadCat()
        loadSubCat()
        loadAssetType()
        initData()
    }, [selectedIndex])

    useEffect(() => {
        let isProper = false
        if (selectedIndex === 2) {
            isProper = [contents, price, selected_asset_type.value, selected_deposit_asset_type.value, selected_cat.value].every( elem => elem !== '')
        } else {
            isProper = [contents, price, selected_asset_type.value, selected_cat.value].every( elem => elem !== '')
        }

        if (isProper) {
            setDisabled(false)
        } else {
            setDisabled(true)
        }

    }, [contents, price, selected_asset_type, selected_deposit_asset_type, selected_cat, selected_subcat])

    const initData = () => {
        setSelected_asset_type(INIT_ASSETSTYPE)
        setSelected_cat(INIT_CATEGORY)
        setSelected_subcat(INIT_SUBCATEGORY)
    }

    const insertData = async () => {
        try {
            let type = selectedIndex + 1;
            if (type === 3) {
                await moneyApi.insertMoney([type, date, contents, -price, selected_asset_type.id, selected_cat.id, selected_subcat.id])
                await moneyApi.insertMoney([type, date, contents, price, selected_deposit_asset_type.id, selected_cat.id, selected_subcat.id])
            } else {
                await moneyApi.insertMoney([type, date, contents, price, selected_asset_type.id, selected_cat.id, selected_subcat.id])
            }
            setSuccess(true)
        } catch (error) {
            console.log('error in insert data', error)
        }
    }

    const loadCat = async () => {
        try {
            const catArray = await moneyApi.selectCategories(selectedIndex + 1)
            setCategories(catArray);
        } catch (error) {
            console.log('error in load categories ( postMoney.js )', error)
        }
    }

    const loadSubCat = async () => {
        try {
            const subCatArray = await moneyApi.selectSubCategories()
            setSubcategories(subCatArray);
        } catch (error) {
            console.log('error in load categories ( postMoney.js )', error)
        }
    }

    const loadAssetType = async () => {
        try {
            const assetsTypeArray = await moneyApi.selectAssetsType()
            setAsset_type(assetsTypeArray);
        } catch (error) {
            console.log('error in load assets type ( postMoney.js )', error)
        }
    }

    const onUpdateCatPress = () => {
        navigation.navigate('EditOption', selectedIndex + 1)
    }

    const onUpdateAssetPress = () => {
        navigation.navigate('EditOption', 0)
    }

    if (success) {
        navigation.goBack()
    }

    return (
        <TouchableWithoutFeedback onPress={() => {
            Keyboard.dismiss();
        }}>
            <View style={{ flex: 1 }}>
                <View>
                    <ButtonsForm
                        onPress={(index) => {setSelectedIndex(index); Keyboard.dismiss();}}
                        selectedIndex={selectedIndex}
                        group={["수입", "지출", "이동"]} />
                    <DatePicker
                        inputTitle="날짜"
                        date={date}
                        setDate={setDate}
                    />
                    <InputBox
                        inputTitle="내용"
                        placeholder="내용을 입력하세요"
                        value={contents}
                        onChangeText={
                            (contents) => setContents(contents)
                        }
                        maxLength={30}
                    />
                    <InputBox
                        inputTitle="금액"
                        placeholder="금액을 입력하세요"
                        value={price}
                        onChangeText={
                            (price) => setPrice(price)
                        }
                        keyboardType="numeric"
                        maxLength={30}
                    />
                    <SelectForm
                        inputTitle={selectedIndex === 2 ? "출금" : "자산"}
                        placeholder="자산 선택"
                        data={asset_type}
                        selectedData={selected_asset_type}
                        onValueChange={(asset) => setSelected_asset_type(asset)}
                        onUpdateDataPress={onUpdateAssetPress}
                    />
                    {selectedIndex === 2 &&
                        <SelectForm
                            inputTitle="입금"
                            placeholder="자산 선택"
                            data={asset_type}
                            selectedData={selected_deposit_asset_type}
                            onValueChange={(deposit_asset) => setSelected_deposit_asset_type(deposit_asset)}
                            onUpdateDataPress={onUpdateAssetPress}
                        />}
                    <SelectForm
                        inputTitle="구분"
                        placeholder="카테고리 선택"
                        data={categories}
                        selectedData={selected_cat}
                        onValueChange={(cat) => setSelected_cat(cat)}
                        subData={subcategories}
                        selectedSubData={selected_subcat}
                        onSubValueChange={(subcat) => setSelected_subcat(subcat)}
                        onUpdateDataPress={onUpdateCatPress}
                    />
                </View>
                <View style={style.buttonRow}>
                    <StyledButton
                        name="저장하기"
                        onPress={insertData}
                        style={style.submitButton}
                        disabled={disabled}
                    />
                    <StyledButton
                        name="취소"
                        onPress={() => navigation.goBack()}
                        style={style.cancelButton}
                    />
                </View>
            </View>
        </TouchableWithoutFeedback>
    )
}

const style = StyleSheet.create({
    Font: {
        fontSize: 24
    },
    buttonRow: {
        flexDirection: 'row',
        alignItems: "center",
        marginHorizontal: 10,
        marginVertical: 3,
    },
    submitButton: {
        flex: 3,
        height: 50,
    },
    cancelButton: {
        flex: 1,
        height: 50,
    }
});

export default PostMoney;