import React, { Fragment, useState, useEffect, useLayoutEffect, useContext  } from 'react';
import { ActivityIndicator } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete, fetchPut  } 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 { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { MonthPicker } from '~/Components/UIControls/MonthPicker';

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 renId = navigation.getParam('renId', 0);
  const [currMonth, setCurrMonth] = useState(Util.toDateString());
  const { auth } = useAuth(navigation);
  const { showMessage } = useToast();

  const [ready, setReady] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({});
  // mount
  useEffect(() => {
      fetch();
  }, [editable]);

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

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

  // react hook form initialize
  const { register, setValue, handleSubmit, errors, getValues } = 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/RentalStatus/${siteId}/${renId}`);
        const result = await fetchGet(`api/RentalStatus/${siteId}/${renId}`);
        setData(result);
        setCurrMonth(result.Year + '-' + (result.Month+'').padStart(2,'0'));
        Form.Year = result.Year;
        Form.month = result.Month;
        Form.setFormData(result);
      } catch (error) {
        showMessage(error.message);
      }
    }

    setReady(false);
    setReady(true);
    setLoading(false);
  };

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

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

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

      const submit = { ...form, 
        SiteId: siteId,
        RentalStatusId :renId,
        CmFile: !form.CmFile.IsUpload && !form.CmFile.IsDelete ? null : form.CmFile,
      };
      console.log('submit data', submit);
      try {

        if(action == Form.CREATE){
          const result = await fetchPut('api/RentalStatus', submit);
          showMessage('등록되었습니다.');
        } else {
          const result = await fetchPost(`api/RentalStatus/${siteId}/${renId}`, submit);
          showMessage('저장되었습니다.');
        }

        refreshList();
        if(action == Form.CREATE) {
            navigation.pop();
        } else {
            setEditable(false);
        }      
      } catch (error) {
        showMessage(error.message);
      }
      setLoading(false);
    });
  }

    // delete
    const onDelete = async () => {
      if(loading) {
          showMessage('처리중입니다. 잠시만기다려 주세요.');
          return;
      }
      confirm('삭제','삭제하시겠습니까?', async () => {
          setLoading(true);
          try {
              await fetchDelete(`api/RentalStatus/${siteId}/${renId}`);
 
              showMessage('삭제되었습니다.');
              refreshList();
              navigation.pop();
          } catch(error) {
              showMessage(error.message);
          }
          setLoading(false);
      });
  }
console.log(data);
  return (

    <BottomTabBarLayout>
      {ready ? (
        <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
          <Form.Field>
            <Form.Require style={{width:100}}><Form.Label>월 선택</Form.Label></Form.Require>
            <Form.MonthPicker month={currMonth} placeholder="" monthFormat="YYYY년 MM월" maximumDate="9999-12" editable={editable} onChange={(momentValue, stringValue) => {
              setValue('Year',  momentValue.startOf('month').format('YYYY'), true);
              setValue('Month', momentValue.startOf('month').format('MM'), true);
            }} /> 
          </Form.Field>

           <Form.Field>
              <Form.TitleTop style={{width:100}}><Form.Label>PDF파일</Form.Label></Form.TitleTop>
              <Form.UploadFile type={UploadFileType.File} mimeType="application/pdf" editable={editable} defaultFile={data.CmFile}
                onUpload={(isUpload, result) => {
                    Form.uploadFile('CmFile', isUpload, result);
                }} onDelete={() => {
                    Form.deleteFile('CmFile');
                }} />
          </Form.Field>
          <Form.RegistFile editable={editable} name="CmFile" value={Util.get(data, "CmFile")} />

          <Form.Field>
              <Form.TitleTop style={{width:100}}><Form.Label>첨부파일</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.Regist editable={editable} name="Year" value={ Util.toDate().getFullYear()} rule={{required:'월을 입력하세요.'}} error={errors.Year} />
          <Form.Regist editable={editable} name="Month" value={ Util.toDate().getMonth() + 1} rule={{required:'월을 입력하세요.'}} error={errors.Month} />
          <Form.Regist name="RentalStatusId" />
          <Form.Field style={{height:50}}></Form.Field>
        </Form.Container>
      ) : (
        <Form.Loading />
      )}
    </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 && <Form.CancelEditButton navigation={navigation} />}
                  </Fragment>
              )}
            </Fragment>
        }
      />
    )
  };
};

export default Screen;
