import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { AllTransactionAllCancel } from '@/entities/transaction/ui/all-transaction-all-cancel'
import { AllTransactionPartCancel } from '@/entities/transaction/ui/all-transaction-part-cancel'
import { useAllTransactioCancleMutation } from '@/entities/transaction/api/use-all-transaction-cancel-mutation';
import { HeaderType } from '@/entities/common/model/types';
import { 
  AllTransactionCancelInfoParams,
  AllTransactionCancelInfoResponse,
  AllTransactionCancelParams,
  AllTransactionCancelResponse,
  CancelTabKeys,
  DebtPreventionCancelDisplayInfo,
  DebtPreventionCancelRequestInfo
} from '@/entities/transaction/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { useAllTransactioCancleInfoMutation } from '@/entities/transaction/api/use-all-transaction-cancel-info-mutation';
import { NumericFormat } from 'react-number-format';
import { useStore } from '@/shared/model/store';
import { AllTransactionCancelPreventBond } from '@/entities/transaction/ui/all-transaction-cancel-prevent-bond';
import { snackBar } from '@/shared/lib';
import { useTranslation } from 'react-i18next';

export const AllTransactionCancelPage = () => {
  const { t } = useTranslation();
  const location = useLocation();
  const userInfo = useStore.getState().UserStore.userInfo;
  const tid = location.state.tid;
  const serviceCode = location.state.serviceCode;

  useSetHeaderTitle(t('transaction.cancelTitle'));
  useSetHeaderType(HeaderType.RightClose);
  useSetFooterMode(false);

  // all or part
  const [tabAction, setTabAction] = useState<CancelTabKeys>(CancelTabKeys.All);
  const [debtPreventionCancelDisplayInfo, setDebtPreventionCancelDisplayInfo] = useState<DebtPreventionCancelDisplayInfo | null | undefined>(null);
  const [debtPreventionCancelRequestInfo, setDebtPreventionCancelRequestInfo] = useState<DebtPreventionCancelRequestInfo | null | undefined>(null);
  const [goodsVat, setGoodsVat] = useState<number | null>(null);
  const [isCompoundTax, setIsCompoundTax] = useState<boolean>(false);
  const [isConditionalVatAutoCalcMerchant, setIsConditionalVatAutoCalcMerchant] = useState<boolean>(false);
  const [isNpg, setIsNpg] = useState<boolean>(false);
  const [isVatAutoCalcMerchant, setIsVatAutoCalcMerchant] = useState<boolean>(false);
  const [isVatDisplayed, setIsVatDisplayed] = useState<boolean>(false);
  const [partCancelCl, setPartCancelCl] = useState<boolean>(false);
  const [remainAmount, setRemainAmount] = useState<number>(0);
  const [serviceAmount, setServiceAmount] = useState<number | null>(null);
  const [supplyAmount, setSupplyAmount] = useState<number | null>(null);
  const [taxFreeAmount, setTaxFreeAmount] = useState<number | null>(null);
  const [vatAutoCalcSummary, setVatAutoCalcSummary] = useState<number>(0);
  const [totalCancelAmount, setTotalCancelAmount] = useState<number>(0);
  const [cancelPassword, setCancelPassword] = useState<string>('');
  const [cancelSupplyAmount, setCancelSupplyAmount] = useState<number>(0);
  const [cancelGoodsVat, setCancelGoodsVat] = useState<number>(0);
  const [cancelTaxFreeAmount, setCancelTaxFreeAmount] = useState<number>(0);
  const [cancelServiceAmount, setCancelServiceAmount] = useState<number>(0);

  const [requestSuccess, setRequestSuccess] = useState<boolean>(true);

  const [bankCode, setBankCode] = useState<string>('');
  const [accountNo, setAccountNo] = useState<string>('');
  const [accountHolder, setAccountHolder] = useState<string>('');

  const [cancelPreventBondOn, setCancelPreventBondOn] = useState<boolean>(false);

  const { mutateAsync: transactionCancel } = useAllTransactioCancleMutation();
  const { mutateAsync: allTransactionCancelInfo } = useAllTransactioCancleInfoMutation();

  const callCancelInfo = () => {
    let params: AllTransactionCancelInfoParams = {
      serviceCode: serviceCode,
      tid: tid
    };
    allTransactionCancelInfo(params).then((rs: AllTransactionCancelInfoResponse) => {
      if(rs.debtPreventionCancelDisplayInfo !== null){
        setCancelPreventBondOn(true);
      }
      else{
        setDebtPreventionCancelDisplayInfo(rs.debtPreventionCancelDisplayInfo);
        setDebtPreventionCancelRequestInfo(rs.debtPreventionCancelRequestInfo);
        setGoodsVat(rs.goodsVat);
        setIsCompoundTax(rs.isCompoundTax);
        setIsConditionalVatAutoCalcMerchant(rs.isConditionalVatAutoCalcMerchant);
        setIsNpg(rs.isNpg);
        setIsVatAutoCalcMerchant(rs.isVatAutoCalcMerchant);
        setIsVatDisplayed(rs.isVatDisplayed);
        setPartCancelCl(rs.partCancelCl);
        setRemainAmount(rs.remainAmount);
        setServiceAmount(rs.serviceAmount);
        setSupplyAmount(rs.supplyAmount);
        setTaxFreeAmount(rs.taxFreeAmount);
        setVatAutoCalcSummary(rs.vatAutoCalcSummary);
        
        if(!partCancelCl){
          setTotalCancelAmount(rs.remainAmount);
        }
        else{
          setTotalCancelAmount(0);
        }
      }
      
      // partCancelCl == true ==> 부분취소 버튼 활성화
      // isCompoundTax == true ==> 부분취소의 복합과세 노출
      // debtPreventionCancelDisplayInfo != null => 입금 후 취소 페이지 노출
      // [취소신청]버튼 클릭시
      // debtPreventionCancelDisplayInfo.isCancel == true => 취소api호출
      // debtPreventionCancelRequestInfo 이 값 통쨰로 변조없이 그대로 api에 전달
      // debtPreventionCancelDisplayInfo.isCancel == false => 얼럿만 띄우고 취소요청하면안됨
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
      
    }); 
  };

  const callTransactionCancel = () => {
    if(debtPreventionCancelDisplayInfo?.isCancel === false){
      snackBar('취소요청이 불가능 합니다.');
    }
    else{
      let transactionCancelParams: AllTransactionCancelParams = {
        tid: tid,
        cancelAmount: totalCancelAmount || 0,
        cancelPassword: cancelPassword,
        bankCode: bankCode,
        accountNo: accountNo,
        accountHolder: accountHolder,
        supplyAmount: (!!partCancelCl)? cancelSupplyAmount: (supplyAmount || 0),
        goodsVatAmount: (!!partCancelCl)? cancelGoodsVat: (goodsVat || 0),
        taxFreeAmount: (!!partCancelCl)? cancelTaxFreeAmount: (taxFreeAmount || 0),
        serviceAmount: (!!partCancelCl)? cancelServiceAmount: (serviceAmount || 0),
        clientIp: userInfo.clientAddressIP,
        partCancelCl: partCancelCl,
        isNpg: isNpg,
        serviceCode: serviceCode
      };
      transactionCancel(transactionCancelParams).then((rs: AllTransactionCancelResponse) => {
        console.log(rs);
        setRequestSuccess(true);
      }).catch((e: any) => {
        setRequestSuccess(false);
      });
    }
    
  };
  useEffect(() => {
    callCancelInfo();
  }, []);

  const onClickToChangeTab = (tab: CancelTabKeys) => {
    setTabAction(tab);
  };
  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane pt-46 active">
            <div className="subTab">
              <button
                className={ `subtab-btn ${(tabAction === CancelTabKeys.All)? 'active': ''}` }
                onClick={ () => onClickToChangeTab(CancelTabKeys.All) }
              >{t('transaction.fullCancel')}</button>
              { !!partCancelCl &&
                <button
                  className={ `subtab-btn ${(tabAction === CancelTabKeys.Part)? 'active': ''}` }
                  onClick={ () => onClickToChangeTab(CancelTabKeys.Part) }
                >{t('transaction.partialCancel')}</button>
              }
            </div>
            <div className="cancel-list pt-30">
              { (tabAction === CancelTabKeys.All) &&
                <AllTransactionAllCancel
                  serviceCode={ serviceCode }
                  debtPreventionCancelDisplayInfo={ debtPreventionCancelDisplayInfo }
                  debtPreventionCancelRequestInfo={ debtPreventionCancelRequestInfo }
                  goodsVat={ goodsVat }
                  isCompoundTax={ isCompoundTax }
                  isConditionalVatAutoCalcMerchant={ isConditionalVatAutoCalcMerchant }
                  isNpg={ isNpg }
                  isVatAutoCalcMerchant={ isVatAutoCalcMerchant }
                  isVatDisplayed={ isVatDisplayed }
                  partCancelCl={ partCancelCl }
                  remainAmount={ remainAmount }
                  serviceAmount={ serviceAmount }
                  supplyAmount={ supplyAmount }
                  taxFreeAmount={ taxFreeAmount }
                  vatAutoCalcSummary={ vatAutoCalcSummary }
                  cancelPassword={ cancelPassword }
                  setCancelPassword={ setCancelPassword }
                  bankCode={ bankCode }
                  setBankCode={ setBankCode }
                  accountNo={ accountNo }
                  setAccountNo={ setAccountNo }
                  accountHolder={ accountHolder }
                  setAccountHolder={ setAccountHolder }
                  requestSuccess={ requestSuccess }
                  totalCancelAmount={ totalCancelAmount }
                ></AllTransactionAllCancel>
              }
              { !!partCancelCl && (tabAction === CancelTabKeys.Part) &&
                <AllTransactionPartCancel
                  serviceCode={ serviceCode }
                  debtPreventionCancelDisplayInfo={ debtPreventionCancelDisplayInfo }
                  debtPreventionCancelRequestInfo={ debtPreventionCancelRequestInfo }
                  goodsVat={ goodsVat }
                  isCompoundTax={ isCompoundTax }
                  isConditionalVatAutoCalcMerchant={ isConditionalVatAutoCalcMerchant }
                  isNpg={ isNpg }
                  isVatAutoCalcMerchant={ isVatAutoCalcMerchant }
                  isVatDisplayed={ isVatDisplayed }
                  partCancelCl={ partCancelCl }
                  remainAmount={ remainAmount }
                  serviceAmount={ serviceAmount }
                  supplyAmount={ supplyAmount }
                  taxFreeAmount={ taxFreeAmount }
                  vatAutoCalcSummary={ vatAutoCalcSummary }
                  cancelPassword={ cancelPassword }
                  setCancelPassword={ setCancelPassword }
                  bankCode={ bankCode }
                  setBankCode={ setBankCode }
                  accountNo={ accountNo }
                  setAccountNo={ setAccountNo }
                  accountHolder={ accountHolder }
                  setAccountHolder={ setAccountHolder }
                  cancelSupplyAmount={ cancelSupplyAmount }
                  setCancelSupplyAmount={ setCancelSupplyAmount }
                  cancelGoodsVat={ cancelGoodsVat }
                  setCancelGoodsVat={ setCancelGoodsVat }
                  cancelTaxFreeAmount={ cancelTaxFreeAmount}
                  setCancelTaxFreeAmount={ setCancelTaxFreeAmount }
                  cancelServiceAmount={ cancelServiceAmount }
                  setCancelServiceAmount={ setCancelServiceAmount }
                  requestSuccess={ requestSuccess }
                  totalCancelAmount={ totalCancelAmount }
                  setTotalCancelAmount={ setTotalCancelAmount }
                ></AllTransactionPartCancel>
              }
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={ () => callTransactionCancel() }
              >{t('transaction.submit')}</button>
            </div>
          </div>
        </div>
      </main>
      { !!cancelPreventBondOn &&
        <AllTransactionCancelPreventBond
          cancelPreventBondOn={ cancelPreventBondOn }
          setCancelPreventBondOn={ setCancelPreventBondOn }
          debtPreventionCancelDisplayInfo={ debtPreventionCancelDisplayInfo }
          serviceCode={ serviceCode}
          tid={ tid }
        ></AllTransactionCancelPreventBond>
      }
    </>
  );
};
