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 type = navigation.getParam('type', null);
    const date = navigation.getParam('date', null);
    const id = navigation.getParam('id', null);
    const { auth, userinfo } = useAuth(navigation);

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

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

    // 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]);

    const fetch = async (editable = false) => {
        setLoading(true);
        await session.load();

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

        setLoading(false);
    };

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

    // cancel edit
    const onCancelEdit = async () => {
        setEditable(false);
    };

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

            try {
                if (action == Form.CREATE) {
                    const api = !form.isHolidayType ? `/api/HolidayCustom/${date}` : `/api/Holiday/${date}`;
                    const submit = { ...form, SiteId: siteId, IsUse: true };
                    console.log('submit data', submit);
                    const result = await fetchPut(api, submit);
                    showMessage('등록되었습니다.');
                } else {
                    const api = type == 'C' ? `/api/HolidayCustom/${siteId}/${date}` : `/api/Holiday/${siteId}/${date}`;
                    if (type == 'H') {
                        [form.HolidayMonth, form.HolidayDay] = date.split('-');
                    } else {
                        form.HolidayDate = data.HolidayDate;
                    }

                    const submit = { ...form, SiteId: siteId };
                    console.log('submit data', submit);
                    const result = await fetchPost(api, submit);
                    showMessage('저장되었습니다.');
                }
                refreshList();
                if (action == Form.CREATE) {
                    navigation.pop();
                } else {
                    fetch(false);
                }
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            const api = type == 'C' ? `api/HolidayCustom/${siteId}/${date}` : `api/Holiday/${siteId}/${date}`;
            try {
                await fetchDelete(api);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    console.log('data', data);

    return (
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <Form.Field>
                    <Form.Require style={{ width: 100 }}>
                        <Form.Label>휴일 이름</Form.Label>
                    </Form.Require>
                    <Form.Input
                        placeholder="휴일 이름"
                        defaultValue={data.Name}
                        onChangeText={(text) => setValue('Name', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="Name" rule={{ required: '휴일 이름을 입력하세요.' }} error={errors.Name} />

                <Form.Field>
                    <Form.Title style={{ width: 100 }}>
                        <Form.Label>정기 휴일 여부</Form.Label>
                    </Form.Title>
                    <Form.Switch
                        initialValue={data.isHolidayType}
                        onValueChange={(newValue) => {
                            console.log('newValue', newValue);
                            setValue('isHolidayType', newValue);
                            setData({ ...data, isHolidayType: newValue });
                        }}
                        editable={action==Form.CREATE ? editable : false}
                    />
                </Form.Field>
                <Form.Regist editable={action==Form.CREATE ? editable : false} name="isHolidayType" value={data.isHolidayType} />

                {data.isHolidayType && (
                    <>
                        <Form.Field>
                            <Form.Title style={{ width: 100 }}>
                                <Form.Label>음력 여부</Form.Label>
                            </Form.Title>
                            <Form.Switch
                                initialValue={data.IsLunar}
                                onValueChange={(newValue) => {
                                    console.log('newValue', newValue);
                                    setValue('IsLunar', newValue);
                                }}
                                editable={editable}
                            />
                        </Form.Field>
                        <Form.Regist editable={editable} name="IsLunar" value={data.IsLunar} />
                    </>
                )}
            </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>
                        {!editable && auth.Delete && (
                            <Fragment>
                                <Form.EditButton navigation={navigation} type="primary" />
                                <Form.DeleteButton />
                            </Fragment>
                        )}
                        {editable && auth.Update && (
                            <Fragment>
                                <Form.SaveButton type="primary" />
                                {action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
