import { motion } from 'framer-motion';
import { DetailMotionDuration, DetailMotionStyle, DetailMotionVariants } from "@/entities/common/model/constant";
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';
import { useTranslation } from 'react-i18next';
import { AllTransactionAllCancel } from './all-transaction-all-cancel';
import { AllTransactionPartCancel } from './all-transaction-part-cancel';
import { AllTransactionCancelInfoParams, AllTransactionCancelInfoResponse, AllTransactionCancelParams, CancelTabKeys, DebtPreventionCancelDisplayInfo, DebtPreventionCancelRequestInfo } from '../model/types';
import { useEffect, useState } from 'react';
import { useAllTransactioCancleMutation } from '../api/use-all-transaction-cancel-mutation';
import { useAllTransactioCancleInfoMutation } from '../api/use-all-transaction-cancel-info-mutation';
import { snackBar } from '@/shared/lib';
import { useStore } from '@/shared/model/store';

export interface AllTransactionCancelProps {
  cancelOn: boolean;
  setCancelOn: (cancelOn: boolean) => void;
  serviceCode: string;
  tid: string;
};
export const AllTransactionCancel = ({
  cancelOn,
  setCancelOn,
  serviceCode,
  tid
}: AllTransactionCancelProps) => {
  const { t } = useTranslation();
  const userInfo = useStore.getState().UserStore.userInfo;
  const userMid = useStore.getState().UserStore.mid;
  
  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,
      mid: userMid
    };
    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 => 얼럿만 띄우고 취소요청하면안됨
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
      
    }).catch((e: any) => {
      if(e.response?.data?.error?.message){
        snackBar(e.response?.data?.error?.message);
        return;
      }
    }); 
  };

  const callTransactionCancel = () => {
    if(debtPreventionCancelDisplayInfo?.isCancel === false){
      snackBar(t('transaction.cancel.requestNotPossible'));
    }
    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: any) => {
        console.log(rs);
        if(rs.resultCode === "2024") {
          snackBar(t('transaction.cancel.passwordGroup.pleaseCheckPassword'));
          setRequestSuccess(false);
        } else {
          setRequestSuccess(true);
        }
      }).catch((e: any) => {
        setRequestSuccess(false);
        if(e.response?.data?.error?.message){
          snackBar(e.response?.data?.error?.message);
          return;
        }
      });
    }

  };

  const onClickToClose = () => {
    setCancelOn(false);
  };
  const onClickToChangeTab = (tab: CancelTabKeys) => {
    setTabAction(tab);
  };

  useEffect(() => {
    callCancelInfo();
  }, []);

  return (
    <>
      <motion.div 
        className="full-menu-modal" 
        initial="hidden"
        animate={ (cancelOn)? 'visible': 'hidden' }
        variants={ DetailMotionVariants }
        transition={ DetailMotionDuration }
        style={ DetailMotionStyle }
      >
        <div className="full-menu-container pdw-16">
          <div className="full-menu-header">
            <div className="full-menu-title center">{ t('transaction.cancelTitle') }</div>
            <div className="full-menu-actions">
              <FullMenuClose
                addClass="full-menu-close"
                onClickToCallback={ onClickToClose }
              ></FullMenuClose>
            </div>
          </div>
          <div 
            className="subTab"
            style={{ top: '50px' }}
          >
            <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="option-list pb-86"
            style={{ marginTop: '81px'}}
          >
            { (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>
        <div className="apply-row">
          <button
            className="btn-50 btn-blue flex-1"
            onClick={ () => callTransactionCancel() }
          >{t('transaction.submit')}</button>
        </div>
      </motion.div>
    </>
  );
};