import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator } 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);
    console.log('id', id);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    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]);

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

        if (action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/Department/${id[0]}/${id[1]}/${id[2]}`);
                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);
    };

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

            try {
                if (action == Form.CREATE) {
                    const submit = { ...form, SiteId: siteId, IsUse: true };
                    console.log('submit data', submit);
                    const result = await fetchPut('api/Department', submit);
                    showMessage('등록되었습니다.');
                } else {
                    const submit = { ...form, SiteId: siteId, DepartmentId: data.DepartmentId, IsUse: data.IsUse };
                    console.log('submit data', submit);
                    const result = await fetchPost(`api/Department/${id[0]}/${id[1]}/${id[2]}`, 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);
            try {
                await fetchDelete(`api/Department/${id[0]}/${id[1]}/${id[2]}`);

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

    return (
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <Form.Field>
                    <Form.Require>
                        <Form.Label>회사 명칭</Form.Label>
                    </Form.Require>
                    <Form.EntitySelect
                        entity="CmCompany"
                        id="CompanyId"
                        defaultLabel="회사 명칭"
                        selectedValue={data.CompanyId}
                        siteId={siteId}
                        editable={editable}
                        useCheck={true}
                        onChange={(item) => {
                            setValue('CompanyId', item.value, true);
                        }}
                    />
                </Form.Field>
                <Form.Regist
                    editable={editable}
                    name="CompanyId"
                    rule={{ required: '회사 명칭을 선택해주세요.' }}
                    error={errors.EquipmentTypeId}
                />

                <Form.Field>
                    <Form.Require>
                        <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>
                        <Form.Label>부서 별칭</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="부서 별칭"
                        defaultValue={data.ShortName}
                        onChangeText={(text) => setValue('ShortName', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="ShortName" />

                <Form.Field>
                    <Form.Title>
                        <Form.Label>부서 전화</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="부서 전화"
                        defaultValue={data.PhoneNo}
                        onChangeText={(text) => setValue('PhoneNo', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="PhoneNo" />

                <Form.Field>
                    <Form.Title>
                        <Form.Label>팩스 번호</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="팩스 번호"
                        defaultValue={data.FaxNo}
                        onChangeText={(text) => setValue('FaxNo', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="FaxNo" />

                <Form.Field>
                    <Form.Title>
                        <Form.Label>비고</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="비고"
                        defaultValue={data.Comment}
                        onChangeText={(text) => setValue('Comment', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="Comment" />

                <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>
                        {!editable && (
                            <Fragment>
                                {auth.Update && <Form.EditButton navigation={navigation} type="primary" />}
                                {auth.Delete && <Form.DeleteButton />}
                            </Fragment>
                        )}
                        {editable && (
                            <Fragment>
                                {auth.Update && <Form.SaveButton type="primary" />}
                                {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
