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

function MemoDetails({ route, navigation }) {
    const { item, loadMemos } = route.params
    const getDates = () => {
        const date = new Date();
        return (getDateStr(date))
    }
    const [date, setDate] = useState(getDates())
    const [message, setMessage] = useState('')
    const onUpdateHandle = async () => {
        await memoApi.updateMemo({ date, message }, item.id)
        loadMemos()
        navigation.navigate('MemoPage')
    }

    useEffect(() => {
        setDate(String(item.date))
        setMessage(item.message)
    }, [])

    return (
        <TouchableWithoutFeedback onPress={() => {
            Keyboard.dismiss();
        }}>
            <View style={{ flex: 1 }}>
                <View>
                    <DatePicker
                        inputTitle="날짜"
                        date={date}
                        setDate={setDate}
                    />
                    <InputBox
                        inputTitle="내용"
                        value={message}
                        onChangeText={
                            (message) => setMessage(message)
                        }
                    />

                </View>
                <View style={style.buttonRow}>
                    <StyledButton
                        name="수정"
                        onPress={() => { onUpdateHandle() }}
                        style={style.submitButton}
                    />
                </View>
            </View>
        </TouchableWithoutFeedback>
    )
}

const style = StyleSheet.create({

    buttonRow: {
        flexDirection: 'row',
        alignItems: "center",
        marginHorizontal: 10,
        marginVertical: 3,
    },
    submitButton: {
        flex: 1,
        height: 50,
    },
    cancelButton: {
        flex: 1,
        height: 50,
    }
});

export default MemoDetails;