import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';
import { TouchableOpacity } from 'react-native-gesture-handler';
import Theme from '~/Themes';
import IconSelect from './IconSelect';
import { View } from 'react-native';

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 shortcutId = navigation.getParam('shortcutId', '');
    const type = 1;
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

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

    // 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(() => {
        /* useFormFunctions 에서 useContext 사용 Provider 의 변경사항 구독하여 갱신시 다시 regist 후 data 를 setValue 처리 */
        //useFormFunctions(register, setValue, data);
        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/app/MobileShortcut/Get?shortcutId=${shortcutId}`);
                setData(result);
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        Form.setFormData(data);
        setEditable(true);
    }

    // cancel edit
    const onCancelEdit = async () => {
        Form.setFormData(data);
        setEditable(false);
    }

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

            try {
                const result = await fetchPost('api/app/MobileShortcut/Save', submit);

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

    const values = getValues();
    console.log('values : ', values);
    console.log('errors : ', errors);
    const SvgIcon = Util.svg(values["Icon"]);
    const borderStyle = editable ? { borderColor: Theme.COLORS.EDITABLE_BORDER } : { borderColor: Theme.COLORS.READONLY_BORDER };

    return ( 
        <BottomTabBarLayout>
            {/* Container 에서 Context Provider 사용 */}
            <Form.Container onSave={handleSubmit(onSave)} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>

                <Form.Field>
                    <Form.Require><Form.Label>메뉴</Form.Label></Form.Require>
                    <Form.EntitySelect entity="Sitemap" id="SitemapId" name="Name" defaultLabel="메뉴" 
                        where="Type = 2 AND Path IS NOT NULL AND Path != ''"
                        selectedValue={data.SitemapId} editable={editable}
                        onChange={(item) => { setValue('SitemapId', item.value, true) }}  />
                </Form.Field>
                {/* Regist 시 useContext 사용 Provider 에 등록 알림 */}
                <Form.Regist editable={editable} name="SitemapId" rule={{required:'메뉴를 선택하세요.'}} error={errors.SitemapId} />

                <Form.Field>
                    <Form.RequireTop><Form.Label>아이콘</Form.Label></Form.RequireTop>
                    <Form.Group style={{flexDirection:'row'}}>
                        <TouchableOpacity style={[{width:80, height:80, borderWidth:1, borderRadius:5, alignItems:'center', justifyContent:'center'}, borderStyle]}
                            onPress={() => {
                                if(editable) {
                                    openPopup(IconSelect, {}, (result) => {
                                        console.log('popup result : ', result);
                                        setValue('Icon', result.Path, true);
                                        setData({...data});
                                    });
                                }
                            }}>
                            {SvgIcon && (
                                <SvgIcon width={60} height={60} />
                            )}
                        </TouchableOpacity>
                    </Form.Group>
                    <View style={{flex:1}} />
                </Form.Field>
                <Form.Regist editable={editable} name="Icon" rule={{required:'아이콘을 선택하세요.'}} error={errors.Icon} />

                <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" />)}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && (<Form.SaveButton type="primary" />)}
                            {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;