import React, { Fragment, useState, useEffect, useLayoutEffect, useRef } from 'react';
import Styled from 'styled-components/native';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import { DefaultButton, PrimaryButton } from '~/Components/Listing/Search';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { Tab, TabHeader, TabTitleGroup, TabContent, TabItem, TabTitle } from '~/Components/UIControls/Tab';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { useForm } from 'react-hook-form';
import { useToast, confirm } from '~/Components/UIControls/Message';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import WorkHistoryMaterials from './WorkHistoryMaterials';
import session from '~/Utils/session';
import { usePrevious } from '~/Components/Hooks';

export default WorkHistoryForm = ({siteId, workRequestId, checkItemId=0, startDate=null, endDate=new Date, readonly=false, auth, popup=DefaultAction}) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({
        CheckDate: endDate,
        WorkProgressId: 4,
    });
    const [materials, setMaterials] = useState([]);
    const [tab, setTab] = useState('info');
    const isCreate = checkItemId == 0 ? true : false;
    const [editable, setEditable] = useState(!auth.Update ? false : (readonly ? false : (isCreate ? true : false)));
    const { showMessage } = useToast();

    console.log('checkItemId : ' + checkItemId);

    useEffect(() => {
        if(!isCreate) {
            fetch(editable);
        }
    }, []);

    console.log('isCreated:',isCreate,', editable:', editable);

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

        if(!isCreate) {
            try {
                const result = await fetchGet(`api/app/WorkResult/GetCheckItem?siteId=${siteId}&workRequestId=${workRequestId}&checkItemId=${checkItemId}`);
                console.log('fetch result : ',result);
                setData(result);
                setMaterials(result.FmsWorkResultCheckItemMaterial);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // react-hook-form init
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);

    // header button handler
    const actionHandler = (action, parameter = {}) => {
        console.log(`action : ${action}`);

        const actions = {
            save: () => {
                const submit = handleSubmit(save);
                submit();
            },
            close: () => {
                console.log('close...');
                popup.close();
            },
        }
        actions[action]();
    }

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

            let error = null;
            try {
                const result = await fetchPost('api/app/WorkResult/SaveCheckItem', submit);
            } catch(e) {
                error = e;
            }

            console.log('error - ', error);

            if(error) {
                showMessage(error.message);
            } else {
                console.log('work history form save success................ popup.select...........................');
                popup.select({IsComplete:submit.IsComplete, IsHold: submit.IsHold});
                showMessage('저장되었습니다.');
            }
            setLoading(false);
        });
    }

    return (
        <PopupLayout title={`작업이력${isCreate?"추가":(editable?"변경":"")}`} header={Header} 
            headerProps={{isCreate, readonly, editable, setEditable, actionHandler, auth}}>
            <Tab>
                <TabHeader>
                    <TabTitleGroup top={true}>
                        <TabTitle onPress={() => {
                            setTab('info');
                        }} active={tab=='info'?true:false} title="작업내용" />
                        <TabTitle onPress={() => {
                            setTab('materials');
                        }} active={tab=='materials'?true:false} title="자재목록" />
                    </TabTitleGroup>
                </TabHeader>
                <TabContent>
                    <TabItem active={tab=='info'?true:false}>
                        <Form.Container noEvent={true}>
                            <Form.Field>
                                <Form.Require><Form.Label>작업일</Form.Label></Form.Require>
                                <Form.DatePicker 
                                    date={data.CheckDate} 
                                    minimumDate={startDate}
                                    onChange={(newDate) => {
                                        setValue('CheckDate', newDate, true);
                                    }} 
                                    editable={editable} />
                            </Form.Field>
                            <Form.Regist editable={editable} name="CheckDate" value={data.CheckDate} rule={{required:'작업일을 선택하세요.'}} error={errors.CmFile1} />

                            <Form.Field>
                                <Form.Require><Form.Label>작업내용</Form.Label></Form.Require>
                                <Form.Input placeholder="작업내용" defaultValue={data.TextResult} onChangeText={text => {
                                    setValue('TextResult', text, true);
                                }} editable={editable} />
                            </Form.Field>
                            <Form.Regist editable={editable} name="TextResult" value={data.TextResult} rule={{required:'작업내용을 입력하세요.'}} error={errors.TextResult} />

                            <Form.Field>
                                <Form.TitleTop><Form.Label>첨부파일1</Form.Label></Form.TitleTop>
                                <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.CmFile1}
                                onUpload={(isUpload, result) => {
                                    Form.uploadFile('CmFile1', isUpload, result);
                                }} onDelete={() => {
                                    Form.deleteFile('CmFile1');
                                }} />
                            </Form.Field>
                            <Form.RegistFile editable={editable} name="CmFile1" value={Util.get(data, "CmFile1")} />

                            <Form.Field>
                                <Form.TitleTop><Form.Label>첨부파일2</Form.Label></Form.TitleTop>
                                <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.CmFile2}
                                onUpload={(isUpload, result) => {
                                    Form.uploadFile('CmFile2', isUpload, result);
                                }} onDelete={() => {
                                    Form.deleteFile('CmFile2');
                                }} />
                            </Form.Field>
                            <Form.RegistFile editable={editable} name="CmFile2" value={Util.get(data, "CmFile2")} />

                            <Form.Field style={{ height:30 }}>
                            </Form.Field>
                        </Form.Container>
                    </TabItem>
                    <TabItem active={tab=='materials'?true:false}>
                        <WorkHistoryMaterials siteId={siteId} workRequestId={workRequestId} 
                            materials={materials} setMaterials={setMaterials} editable={editable} />
                    </TabItem>
                </TabContent>
            </Tab>
            {loading && <Form.Loading />}
        </PopupLayout>
    )
}

const Header = ({isCreate, readonly, editable, setEditable, actionHandler, auth}) => {

    return (
        <Fragment>
            {(() => {
                if(isCreate) {
                    return (
                        <Fragment>
                            {auth.Update && <PrimaryButton onPress={() => { actionHandler('save') }}>저장</PrimaryButton>}
                            <DefaultButton onPress={() => { actionHandler('close') }}>닫기</DefaultButton>
                        </Fragment>
                    )
                } else {
                    if(editable) {
                        return (
                            <Fragment>
                                {auth.Update && <PrimaryButton onPress={() => { actionHandler('save') }}>저장</PrimaryButton>}
                                {auth.Update && <DefaultButton onPress={() => { setEditable(false) }}>취소</DefaultButton>}
                                <DefaultButton onPress={() => { actionHandler('close') }}>닫기</DefaultButton>
                            </Fragment>
                        )
                    } else {
                        return (
                            <Fragment>
                                {auth.Update && !readonly && <PrimaryButton onPress={() => { setEditable(true) }}>편집</PrimaryButton>}
                                <DefaultButton onPress={() => { actionHandler('close') }}>닫기</DefaultButton>
                            </Fragment>
                        )
                    }
                }
            })()}
        </Fragment>
    )
}
