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 depth = navigation.getParam('depth', 0);
    const parent = navigation.getParam('parent', null);

    console.log('id', id);

    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 {
                const result = await fetchGet(`api/MaterialCodeClass/${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);

            try {
                if (action == Form.CREATE) {
                    const submit = {
                        ...form,
                        Depth: depth,
                        IsUse: true,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPut('api/MaterialCodeClass', submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    navigation.pop();
                } else {
                    const submit = {
                        ...form,
                        MaterialClassId: id[0],
                        IsUse: true,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPost(`api/MaterialCodeClass/${id[0]}`, submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    navigation.pop();
                }
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/MaterialCodeClass/${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.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.Regist editable={editable} name="ParentMaterialClassId" value={parent} />

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

export default Screen;
