import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { CashReceiptHandWrittenIssuanceStep1 } from '@/entities/transaction/ui/cash-receipt-hand-written-issuance-step1';
import { CashReceiptHandWrittenIssuanceStep2 } from '@/entities/transaction/ui/cash-receipt-hand-written-issuance-step2';
import { CashReceiptPurposeType, ProcessStep } from '@/entities/transaction/model/types';
import { HeaderType} from '@/entities/common/model/types';
import { useSetFooterMode, useSetHeaderTitle, useSetHeaderType } from '@/widgets/sub-layout/use-sub-layout';
import { useCashReceiptManualIssueMutation } from '@/entities/transaction/api/use-cash-receipt-manual-issue-mutation';
import { showAlert } from '@/widgets/show-alert';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib';

export const CashReceitHandWrittenIssuancePage = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  let businessInfo = useStore.getState().UserStore.businessInfo;
  let userMid = useStore.getState().UserStore.mid;
  // 1 or 2
  const [processStep, setProcessStep] = useState<ProcessStep>(ProcessStep.One);
  const [businessNumber, setBusinessNumber] = useState<string>(businessInfo.companyNumber);
  const [purposeType, setPurposeType] = useState<CashReceiptPurposeType>(CashReceiptPurposeType.INCOME_DEDUCTION);
  const [productName, setProductName] = useState<string>('');
  const [buyerName, setBuyerName] = useState<string>('');
  const [issueNumber, setIssueNumber] = useState<string>('');
  const [email, setEmail] = useState<string>('');
  const [phoneNumber, setPhoneNumber] = useState<string>('');
  const [issueAmount, setIssueAmount] = useState<number>(0);
  const [supplyAmount, setSupplyAmount] = useState<number>(0);
  const [vatAmount, setVatAmount] = useState<number>(0);
  const [taxFreeAmount, setTaxFreeAmount] = useState<number>(0);
  const [serviceCharge, setServiceCharge] = useState<number>(0);

  useSetHeaderTitle(t('cashReceipt.manualIssuance'));
  useSetHeaderType(HeaderType.RightClose);
  useSetFooterMode(false);

  const { mutateAsync: cashReceiptManualIssue } = useCashReceiptManualIssueMutation();
  
  const checkEmail = (email: string) => {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if(email != '' && email != 'undefined' && re.test(email)){
      return true;
    }
    else{
      return false;
    }
  };

  const callManualIssue = () => {
    let params = {
      mid: userMid,
      businessNumber: businessNumber,
      purpose: purposeType,
      productName: productName,
      buyerName: buyerName,
      issueNumber: issueNumber,
      email: email,
      phoneNumber: phoneNumber,
      supplyAmount: supplyAmount,
      vatAmount: vatAmount,
      taxFreeAmount: taxFreeAmount,
      serviceCharge: serviceCharge
    };
    cashReceiptManualIssue(params).then((rs) => {
      console.log(rs);
      snackBar('수기 신청이 완료되었습니다.', function(){
        navigate(PATHS.transaction.cashReceipt.list);
      }, 3000);
    });
  };

  const onClickToVatCalculate = () => {
    let amount = parseInt((issueAmount / 11 * 10).toFixed(0));
    let vat = issueAmount - amount;
    setSupplyAmount(amount);
    setVatAmount(vat);
  };

  const onClickToChangeTab = () => {
    if(processStep === ProcessStep.One){
      if(!businessNumber){
        showAlert('사업자 번호는 필수 입력 항목 입니다.');
        return;
      }
      else if(!productName){
        showAlert('상품명은 필수 입력 항목 입니다.');
        return;
      }
      else if(!buyerName){
        showAlert('구매자는 필수 입력 항목 입니다.');
        return;
      }
      else if(!issueNumber){
        showAlert('발행번호는 필수 입력 항목 입니다.');
        return;
      }
      else if(email && !checkEmail(email)){
        showAlert('이메일 형식이 맞지 않습니다.');
        return;
      }
      else if(!phoneNumber){
        showAlert('전화번호는 필수 입력 항목 입니다.');
        return;
      }
      setProcessStep(ProcessStep.Two);
    }
    else if(processStep === ProcessStep.Two){
      if(supplyAmount <= 0){
        showAlert('공급가액은 1원 이상이어야 합니다.');
        return;
      }
      callManualIssue();
    }
  };

  
  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className="issue-progress">
                <div className="bar">
                  {(processStep === ProcessStep.One) &&
                    <div
                      className="fill"
                      style={{ width: '50%' }}
                    ></div>
                  }
                  {(processStep === ProcessStep.Two) &&
                    <div
                      className="fill"
                      style={{ width: '100%' }}
                    ></div>
                  }
                </div>
              </div>
              { (processStep === ProcessStep.One) &&
                <CashReceiptHandWrittenIssuanceStep1
                  businessNumber={ businessNumber }
                  purposeType={ purposeType }
                  productName={ productName }
                  buyerName={ buyerName }
                  issueNumber={ issueNumber }
                  email={ email }
                  phoneNumber={ phoneNumber }
                  setBusinessNumber={ setBusinessNumber }
                  setPurposeType={ setPurposeType }
                  setProductName={ setProductName }
                  setBuyerName={ setBuyerName }
                  setIssueNumber={ setIssueNumber }
                  setEmail={ setEmail }
                  setPhoneNumber={ setPhoneNumber }
                ></CashReceiptHandWrittenIssuanceStep1>
              }
              { (processStep === ProcessStep.Two) &&
                <CashReceiptHandWrittenIssuanceStep2
                  setProcessStep={ setProcessStep }
                  issueAmount={ issueAmount }
                  supplyAmount={ supplyAmount }
                  vatAmount={ vatAmount }
                  taxFreeAmount={ taxFreeAmount }
                  serviceCharge={ serviceCharge }
                  setIssueAmount={ setIssueAmount }
                  setSupplyAmount={ setSupplyAmount }
                  setVatAmount={ setVatAmount }
                  setTaxFreeAmount={ setTaxFreeAmount }
                  setServiceCharge={ setServiceCharge }
                  onClickToVatCalculate={ onClickToVatCalculate }
                ></CashReceiptHandWrittenIssuanceStep2>
              }
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={ () => onClickToChangeTab() }
              >
                { (processStep === ProcessStep.One) && t('common.next') }
                { (processStep === ProcessStep.Two) && t('cashReceipt.issue') }
              </button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};