import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { 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, Controller } 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';
import { Util } from '~/Utils/utils';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const facilityStateId = navigation.getParam('facilityStateId', 0);
    const { auth } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ IsUse: true });

    // mount
    useEffect(() => {
        fetch();
    }, []);

    // unmount
    useEffect(() => () => {
    }, []);

    // popup
    const { openPopup } = usePopup();

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues, control } = 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/FacilityState/${facilityStateId}`);
                let result = await fetchGet(`api/FacilityState/${facilityStateId}`);

                result.QuestionList = Util.get(result, 'FmsFacilityStateDetailList', []).filter(x => x.Type == 1);
                const replyList = Util.get(result, 'FmsFacilityStateDetailList', []).filter(x => x.Type == 2);
                result.ReplyList = [];
                for(let question of result.QuestionList) {
                    let reply = replyList.find(x => x.Type == 2 && x.QuestionId == question.QuestionId);
                    if(reply == null) {
                        reply = {...question, Content:'', SiteId: siteId, Type: 2};
                    }
                    result.ReplyList.push(reply);
                }
                
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            Form.setFormData(data);
        }

        setLoading(false);
    }

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }

        const submit = {
            FacilityStateId: facilityStateId,
            Title: form.Title,
            StartDate: form.StartDate,
            EndDate: form.EndDate,
            Note: form.Note,
            FmsFacilityStateDetail: [...form.QuestionList, ...form.ReplyList],
        };
        console.log('submit data', submit);
    
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/FacilityState/${facilityStateId}/${siteId}`, submit);

                showMessage('저장되었습니다.');
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    fetch(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} loading={loading}>
                <Form.Field>
                    <Form.Title><Form.Label>질문제목</Form.Label></Form.Title>
                    <Form.Input value={data.Title} editable={false} />
                </Form.Field>
                <Form.Regist name="Title" />

                <Form.Field>
                    <Form.Title><Form.Label>시작일</Form.Label></Form.Title>
                    <Form.Input value={Util.toDateString(data.StartDate)} editable={false} />
                </Form.Field>
                <Form.Regist name="StartDate" />

                <Form.Field>
                    <Form.Title><Form.Label>종료일</Form.Label></Form.Title>
                    <Form.Input value={Util.toDateString(data.EndDate)} editable={false} />
                </Form.Field>
                <Form.Regist name="EndDate" />

                <Form.Field>
                    <Form.Title><Form.Label>비고</Form.Label></Form.Title>
                    <Form.Input value={data.Note} editable={false} />
                </Form.Field>
                <Form.Regist name="Note" />

                {Util.get(data, 'QuestionList', []).map((item, index) => {
                    let reply = Util.get(data, 'ReplyList', []).find(f => f.Type == 2 && f.QuestionId == item.QuestionId);
                    if(!reply) reply = {};

                    return (
                        <Fragment key={`item-${index}`}>
                            <Form.FieldSetHead>
                                <Form.Legend><Form.LegendLabel>항목 {item.QuestionId}</Form.LegendLabel></Form.Legend>
                            </Form.FieldSetHead>
                            <Form.Field style={{ alignSelf:'center', width:'97%'}}>
                                <Form.Input value={item.Content} editable={false} multiline={true} />
                            </Form.Field>
                            <Form.Regist name={`QuestionList[${index}].FacilityStateDetailId`} />
                            <Form.Regist name={`QuestionList[${index}].FacilityStateId`} />
                            <Form.Regist name={`QuestionList[${index}].QuestionId`} />
                            <Form.Regist name={`QuestionList[${index}].Type`} />
                            <Form.Regist name={`QuestionList[${index}].SiteId`} />
                            <Form.Regist name={`QuestionList[${index}].Content`} />

                            <Fragment>
                                <Form.Field style={{ alignSelf:'center', width:'97%'}}>
                                    <Form.Input defaultValue={reply.Content} editable={true} multiline={true} 
                                        onChangeText={(text) => {
                                            setValue(`ReplyList[${index}].Content`, text);
                                        }}
                                    />
                                </Form.Field>
                                <Form.Regist name={`ReplyList[${index}].FacilityStateDetailId`} />
                                <Form.Regist name={`ReplyList[${index}].FacilityStateId`} />
                                <Form.Regist name={`ReplyList[${index}].QuestionId`} />
                                <Form.Regist name={`ReplyList[${index}].Type`} />
                                <Form.Regist name={`ReplyList[${index}].SiteId`} />
                                <Form.Regist name={`ReplyList[${index}].Content`} />
                            </Fragment>
                        </Fragment>
                    );
                })}

                <Form.Field style={{ height:30 }}>
                </Form.Field>

            </Form.Container>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`정보조사(설문)`}
                main={false}
                buttons={
                    <Fragment>
                        {auth.Update && (<Form.SaveButton type="primary" />)}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;