import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } 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';

const getDate = () => {
    var date = new Date();
    return (String(date.toJSON()).split(/T/)[0])
}

const INIT_SUBCATEGORIES = [
    {
        id: 1,
        value: '간식',
        foreign_id: 1
    },
    {
        id: 2,
        value: '외식',
        foreign_id: 1
    },
    {
        id: 3,
        value: '배달',
        foreign_id: 1
    },
    {
        id: 4,
        value: '택시',
        foreign_id: 2
    },
    {
        id: 5,
        value: '영화',
        foreign_id: 3
    },
    {
        id: 6,
        value: '뮤지컬',
        foreign_id: 3
    },
]

const PostMoney = () => {
    const [selectedIndex, setSelectedIndex] = useState(0)
    const [date, setDate] = useState(getDate())
    const [contents, setContents] = useState('')
    const [price, setPrice] = useState(0)
    const [asset_type, setAsset_type] = useState([])
    const [selected_asset_type, setSelected_asset_type] = useState(0)
    const [categories, setCategories] = useState([])
    const [selected_cat, setSelected_cat] = useState(0)
    const [subcategories, setSubcategories] = useState(INIT_SUBCATEGORIES)
    const [selected_subcat, setSelected_subcat] = useState(0)

    console.log('type: ', selectedIndex, '| date: ', date, '| contents: ', contents, '| price: ', price, '| selected_asset_type: ', selected_asset_type, '| selected_cat: ', selected_cat, '| selected_subcat: ', selected_subcat)

    const insertData = async () => {
        try {
            let type = ''

            if (selectedIndex === 0) { type = '수입' }
            else if (selectedIndex === 1) { type = '지출' }
            else { type = '이동' }

            const result = await moneyApi.insertMoney([type, date, contents, price, selected_asset_type, selected_cat, selected_subcat])
            console.log(result)
        } catch (error) {
            console.log('error in insert data', error)
        }
    }

    const loadCat = async () => {
        try {
            const catArray = await moneyApi.selectCategories()
            console.log('catload', catArray)
            setCategories(catArray);
        } 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)
        }
    }


    useEffect(() => {
        loadCat()
        loadAssetType()
    }, [])

    return (
        <View>
            <View>
                <ButtonsForm
                    onPress={(index) => setSelectedIndex(index)}
                    selectedIndex={selectedIndex}
                    group={["수입", "지출", "이동"]} />
                <DatePicker
                    inputTitle="날짜"
                    date={date}
                    setDate={setDate}
                />
                <InputBox
                    inputTitle="내용"
                    placeholder="내용을 입력하세요"
                    onChangeText={
                        (contents) => setContents(contents)
                    }
                    maxLength={30}
                />
                <InputBox
                    inputTitle="금액"
                    placeholder="금액을 입력하세요"
                    onChangeText={
                        (price) => setPrice(price)
                    }
                    keyboardType="numeric"
                    maxLength={30}
                />
                <SelectForm
                    inputTitle="자산"
                    placeholder="자산 선택"
                    data={asset_type}
                    selectedData={selected_asset_type}
                    onValueChange={(assetId) => setSelected_asset_type(assetId)}
                />
                <SelectForm
                    inputTitle="구분"
                    placeholder="카테고리 선택"
                    data={categories}
                    selectedData={selected_cat}
                    onValueChange={(catId) => setSelected_cat(catId)}
                    subData={subcategories}
                    selectedSubData={selected_subcat}
                    onSubValueChange={(subcatId) => setSelected_subcat(subcatId)}
                />
            </View>
            <View style={style.buttonRow}>
                <StyledButton
                    name="저장하기"
                    onPress={insertData}
                    style={style.submitButton}
                />
                <StyledButton
                    name="취소"
                    onPress={() => console.log('취소버튼')}
                    style={style.cancelButton}
                />
            </View>
        </View>
    )
}

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;