import React, { Fragment, useState, useEffect, useLayoutEffect } from 'react';
import { ActivityIndicator } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import { useToast } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { useAuth } from '~/Components/Hooks';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const siteId = navigation.getParam('siteId', '');
    const buildingId = navigation.getParam('buildingId', '');
    const floorId = navigation.getParam('floorId', '');
    const { auth, userinfo } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [editable, setEditable] = useState(action == Form.VIEW ? false : true);
    const [data, setData] = useState({});
    const { showMessage } = useToast();

    useEffect(() => {
        fetch();
    }, []);
    
    // search
    const fetch = async () => {
        setLoading(true);

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/Floor/Get?siteId=${siteId}&buildingId=${buildingId}&floorId=${floorId}`);
                setData(result);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

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

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

    // save
    const { register, setValue, handleSubmit, errors } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);

    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        setLoading(true);
        const submit = {...form,
            SiteId: data.SiteId,
            FloorId: data.FloorId,
        };

        try {
            const result = await fetchPost('api/Floor/Save', submit);
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
        setEditable(false);
        navigation.setParams({ editable: false });
    }

    // delete
    const onDelete = async () => {
        console.log('onDelete');
    }

    return ( 
        <BottomTabBarLayout>
            <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="CmBuilding" siteId={userinfo.SiteId} useCheck={true}
                        defaultLabel="빌딩" selectedValue={data.BuildingId} selectedText={data.BuildingName}
                        onChange={(item) => { setValue('BuildingId', item.value, true) }} editable={editable} />
                </Form.Field>
                <Form.Regist name="BuildingId" rule={{required: '빌딩을 선택하세요.'}} error={errors.BuildingId} />
                
                <Form.Field>
                    <Form.Title><Form.Label>층명칭</Form.Label></Form.Title>
                    <Form.Input defaultValue={data.Name} onChangeText={text => setValue('Name', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist name="Name" rule={{required: '층 명칭을 입력하세요.'}} error={errors.Name} />
            </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);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`층정보`}
                main={false}
                buttons={
                    <Fragment>
                    {/*!editable && (
                        <Fragment>
                            <Form.EditButton onPress={onEdit} type="primary" />
                            <Form.DeleteButton />
                        </Fragment>
                    )*/}
                    {/*editable && (
                        <Fragment>
                            <Form.SaveButton type="primary" />
                            {action != Form.CREATE && <Form.CancelEditButton onPress={onCancelEdit} />}
                        </Fragment>
                    )*/}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;