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

    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/Company/${id[0]}/${id[1]}`);
                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/Company', submit);
                    showMessage('등록되었습니다.');
                } else {
                    const submit = { ...form, SiteId: siteId, CompanyId: data.CompanyId, IsUse: data.IsUse };
                    console.log('submit data', submit);
                    const result = await fetchPost(`api/Company/${id[0]}/${id[1]}`, 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/Company/${id[0]}/${id[1]}`);

                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="CmCompanyType"
                        id="CompanyTypeId"
                        defaultLabel="회사 구분"
                        selectedValue={data.CompanyTypeId}
                        editable={editable}
                        useCheck={true}
                        onChange={(item) => {
                            setValue('CompanyTypeId', item.value, true);
                        }}
                    />
                </Form.Field>
                <Form.Regist
                    editable={editable}
                    name="CompanyTypeId"
                    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.RepresentativeName}
                        onChangeText={(text) => setValue('RepresentativeName', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="RepresentativeName" error={errors.RepresentativeName} />

                <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.SalesName}
                        onChangeText={(text) => setValue('SalesName', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="SalesName" />

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

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

                <Form.Field>
                    <Form.Title>
                        <Form.Label>회사 주소</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="회사 주소"
                        defaultValue={data.Address1}
                        onChangeText={(text) => setValue('Address1', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="Address1" />

                <Form.Field>
                    <Form.Title>
                        <Form.Label>홈페이지</Form.Label>
                    </Form.Title>
                    <Form.Input
                        placeholder="홈페이지"
                        defaultValue={data.Homepage}
                        onChangeText={(text) => setValue('Homepage', text, true)}
                        editable={editable}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="Homepage" />

                <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;
