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 } 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';
import { InputFilters } from '~/Components/UIControls/Input';

const titleWidth = 110;

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 tenantId = navigation.getParam('tenantId', 0);
    const { auth, userinfo } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ IsUse:true });
    const [areaSize, setAreaSize] = useState(0);
    const [exclusiveArea, setExclusiveArea] = useState(0);
    const { showMessage } = useToast();

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

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

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

    const convertToPyung = (value) => {
        return (Util.parseFloat(value) / 3.30579).toFixed(2) + '';
    }
    
    // search
    const fetch = async (editable) => {
        setLoading(true);

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/Tenant/Get?siteId=${siteId}&tenantId=${tenantId}`);
                setData(result);
                setAreaSize(convertToPyung(result.AreaSize));
                setExclusiveArea(convertToPyung(result.ExclusiveArea));
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            Form.setFormData(data);
            setAreaSize(convertToPyung(data.AreaSize));
            setExclusiveArea(convertToPyung(data.ExclusiveArea));
        }

        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        setEditable(true);
        setAreaSize(convertToPyung(data.AreaSize));
        setExclusiveArea(convertToPyung(data.ExclusiveArea));
    }

    // cancel edit
    const onCancelEdit = async () => {
        setEditable(false);
        setAreaSize(convertToPyung(data.AreaSize));
        setExclusiveArea(convertToPyung(data.ExclusiveArea));
    }

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

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

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

    // delete
    const onDelete = async () => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제','삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/app/Tenant/${siteId}/${tenantId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>층명칭</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmFloor" defaultLabel="층명칭" siteId={siteId}
                                selectedValue={data.FloorId} editable={editable}
                                onChange={(item) => { 
                                    setData({...data, FloorId: item.value});
                                    setValue('FloorId', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="FloorId" rule={{required:'층명칭을 선택하세요.'}} error={errors.FloorId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>회사구분</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmCompanyType" defaultLabel="회사구분"
                        selectedValue={data.CompanyTypeId} selectedText={data.CompanyTypeName} editable={editable} useCheck={true}
                        onChange={(item) => { setValue('CompanyTypeId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="CompanyTypeId" rule={{required:'회사구분을 선택하세요.'}} error={errors.CompanyTypeId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>회사명칭</Form.Label></Form.Require>
                    <Form.Input placeholder="회사명칭" defaultValue={data.Name} 
                                onChangeText={text => setValue('Name', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Name" rule={{required:'회사명칭을 입력하세요.'}} error={errors.Name} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>회사대표</Form.Label></Form.Require>
                    <Form.Input placeholder="회사대표" defaultValue={data.RepresentativeName} 
                                onChangeText={text => setValue('RepresentativeName', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="RepresentativeName" rule={{required:'회사대표명을 입력하세요.'}} error={errors.RepresentativeName} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>대표번호</Form.Label></Form.Require>
                    <Form.Input placeholder="대표번호" defaultValue={data.RepresentativePhone} 
                                onChangeText={text => setValue('RepresentativePhone', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="RepresentativePhone" rule={{required:'대표번호를 입력하세요.'}} error={errors.RepresentativePhone} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>팩스번호</Form.Label></Form.Title>
                    <Form.Input placeholder="팩스번호" defaultValue={data.Fax} 
                                onChangeText={text => setValue('Fax', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Fax" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>담당자명</Form.Label></Form.Title>
                    <Form.Input placeholder="담당자명" defaultValue={data.ChargeName} 
                                onChangeText={text => setValue('ChargeName', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="ChargeName" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>담당자전화</Form.Label></Form.Title>
                    <Form.Input placeholder="담당자전화" defaultValue={data.ChargePhone} 
                                onChangeText={text => setValue('ChargePhone', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="ChargePhone" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>담당자이메일</Form.Label></Form.Title>
                    <Form.Input placeholder="담당자이메일" defaultValue={data.ChargeEmail} 
                                onChangeText={text => setValue('ChargeEmail', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="ChargeEmail" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>임대면적</Form.Label></Form.Title>
                    <Form.Input placeholder="임대면적(㎡)" defaultValue={data.AreaSize} 
                                leftText="㎡" editable={editable} returnKeyType="next"
                                filter={(text)=>{
                                    return InputFilters.decimal(text);
                                }}
                                onChangeText={text => {
                                    setValue('AreaSize', text, true);
                                    setAreaSize(convertToPyung(text));
                                }}
                    />
                    <Form.Input placeholder="임대면적(평)" value={areaSize} style={{marginLeft:10}}
                                leftText="평" editable={false}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="AreaSize" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>전용면적</Form.Label></Form.Title>
                    <Form.Input placeholder="전용면적(㎡)" defaultValue={data.ExclusiveArea} 
                                leftText="㎡" editable={editable} returnKeyType="next"
                                filter={(text)=>{
                                    return InputFilters.decimal(text);
                                }}
                                onChangeText={text => {
                                    setValue('ExclusiveArea', text, true);
                                    setExclusiveArea(convertToPyung(text));
                                }}
                    />
                    <Form.Input placeholder="전용면적(평)" value={exclusiveArea} style={{marginLeft:10}}
                                leftText="평" editable={false}
                    />
                </Form.Field>
                <Form.Regist editable={editable} name="ExclusiveArea" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>우편번호</Form.Label></Form.Title>
                    <Form.Input placeholder="우편번호" defaultValue={data.AddressZip} 
                                onChangeText={text => setValue('AddressZip', text, true)} 
                                editable={editable} returnKeyType="next" keyboardType="number-pad" />
                </Form.Field>
                <Form.Regist editable={editable} name="AddressZip" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>회사주소</Form.Label></Form.Title>
                    <Form.Input placeholder="주소" defaultValue={data.Address1} 
                                onChangeText={text => setValue('Address1', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Address1" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label></Form.Label></Form.Title>
                    <Form.Input placeholder="상세주소" defaultValue={data.Address2} 
                                onChangeText={text => setValue('Address2', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Address2" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>홈페이지</Form.Label></Form.Title>
                    <Form.Input placeholder="홈페이지" defaultValue={data.AddressZip} 
                                onChangeText={text => setValue('AddressZip', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="AddressZip" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>비고</Form.Label></Form.Title>
                    <Form.Input placeholder="비고" defaultValue={data.AddressZip} 
                                onChangeText={text => setValue('AddressZip', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="AddressZip" />

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

export default Screen;