import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPut, fetchPost, 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 { useAuth } from '~/Components/Hooks';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { Util } from '~/Utils/utils';

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 [ready, setReady] = useState(false);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const { showMessage } = useToast();
    const { auth, config } = useAuth(navigation);

    // mount
    useEffect(() => {
        fetch();
    }, [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 () => {
        setLoading(true);
        await session.load();

        if (action != Form.CREATE) {
            try {
                console.log('get - ', `api/MaterialWarehouse/${id[0]}/${id[1]}`);
                const result = await fetchGet(`api/MaterialWarehouse/${id[0]}/${id[1]}`);
                console.log(result);
                setData(result);
                Form.setFormData(result);
            } catch (error) {
                showMessage(error.message);
            }
        }

        setReady(false);
        setReady(true);
        setLoading(false);
    };

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

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

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

            try {
                if (action == Form.CREATE) {
                    const result = await fetchPut('api/MaterialWarehouse', submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    navigation.pop();
                } else {
                    const result = await fetchPost(`api/MaterialWarehouse/${id[0]}/${id[1]}`, submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    setEditable(false);
                }
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/MaterialWarehouse/${id[0]}/${id[1]}`);

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

    return (
        <BottomTabBarLayout>
            {ready ? (
                <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="CmBusinessField"
                            defaultLabel="업무분야"
                            selectedValue={data.BusinessFieldId}
                            selectedText={Util.get(data, 'CmBusinessField.Name')}
                            editable={editable}
                            useCheck={true}
                            auth={auth}
                            onChange={(item) => {
                                setValue('BusinessFieldId', item.value, true);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist
                        editable={editable}
                        name="BusinessFieldId"
                        rule={{ required: '업무분야를 선택하세요.' }}
                        error={errors.BusinessFieldId}
                    />

                    <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.EntitySelect
                            entity="CmFloor"
                            defaultLabel="층"
                            id="FloorId"
                            siteId={siteId}
                            selectedValue={data.FloorId}
                            selectedText={Util.get(data, 'CmFloor.Name')}
                            editable={editable}
                            onChange={(item) => {
                                setData({
                                    ...data,
                                    FloorId: item.value,
                                });
                                setValue('FloorId', item.value, true);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="FloorId" error={errors.FloorId} />

                    <Form.Field>
                        <Form.Title>
                            <Form.Label>구역</Form.Label>
                        </Form.Title>
                        <Form.EntitySelect
                            entity="CmZone"
                            defaultLabel="구역"
                            id="ZoneId"
                            siteId={siteId}
                            where={`FloorId = ${data.FloorId ? data.FloorId : -1}`}
                            selectedValue={data.ZoneId}
                            selectedText={Util.get(data, 'CmZone.Name')}
                            editable={editable}
                            onChange={(item) => {
                                setValue('ZoneId', item.value, true);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="ZoneId" error={errors.ZoneId} />

                    <Form.Field style={{ height: 30 }}></Form.Field>
                </Form.Container>
            ) : (
                <Form.Loading />
            )}
        </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;
