import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator,Text } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchPut, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const setEditable = (value) => { navigation.setParams({editable: value}) };
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const id = navigation.getParam('id', null);
    const { auth, userinfo } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const { showMessage } = useToast();

    // mount
    useEffect(() => {
        fetch(true);
    }, []);

    // change editable
    useEffect(() => {
    }, [editable]);

    // unmount
    useEffect(() => () => {
    }, []);

    // popup
    const { openPopup } = usePopup();

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const fetch = async (editable=false) => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/HolidayWeekend/${siteId}`);
                setData(result);
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        setEditable(true);
    }

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        console.log('form', form);
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            try {
                const submit = {...form,
                    SiteId: siteId,
                    IsUse: true,
                };
                console.log('submit data', submit);
                const result = await fetchPost(`api/HolidayWeekend/${siteId}`, submit);
                showMessage('저장되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }


    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onEdit={onEdit} loading={loading}>
                <Form.Field>
                    <Form.Title style={{width:100}}><Form.Label>토요일 휴일</Form.Label></Form.Title>
                    <Form.Switch initialValue={data.Saturday} onValueChange={(newValue) => { setValue('Saturday', newValue) }} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Saturday" />

                <Form.Field>
                    <Form.Title style={{width:100}}><Form.Label>일요일 휴일</Form.Label></Form.Title>
                    <Form.Switch initialValue={data.Sunday} onValueChange={(newValue) => { setValue('Sunday', newValue) }} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Sunday" />

                <Form.Field style={{ height:30 }}>
                </Form.Field>

            </Form.Container>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`주말설정`}
                main={false}
                buttons={
                    <Fragment>
                        <Form.SaveButton type="primary" />
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;