import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { PATHS } from '@/shared/constants/paths';
import { Dialog } from '@/shared/ui/dialogs/dialog';
import { overlay } from 'overlay-kit';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useAllTransactionDetailMutation } from '@/entities/transaction/api/use-all-transaction-detail-mutation';
import { AmountInfoSection } from '@/entities/transaction/ui/section/amount-info-section';
import { ImportantInfoSection } from '@/entities/transaction/ui/section/important-info-section';
import { PaymentInfoSection } from '@/entities/transaction/ui/section/payment-info-section';
import { TransactionInfoSection } from '@/entities/transaction/ui/section/transaction-info-section';
import { SettlementInfoSection } from '@/entities/transaction/ui/section/settlement-info-section';
import { PartCancelInfoSection } from '@/entities/transaction/ui/section/part-cancel-info-section';
import { 
  TransactionCategory,
  AllTransactionDetailParams,
  DetailResponse,
  AmountInfo,
  ImportantInfo,
  PaymentInfo,
  TransactionInfo,
  SettlementInfo,
  PartCancelInfo,
  InfoSectionKeys
} from '@/entities/transaction/model/types';
import { useTranslation } from 'react-i18next';
import { 
  DetailMotionDuration, 
  DetailMotionStyle, 
  DetailMotionVariants 
} from '@/entities/common/model/constant';
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';
import { checkGrant } from '@/shared/lib/check-grant';
import { showAlert } from '@/widgets/show-alert';
import { snackBar } from '@/shared/lib';

export interface AllTransactionDetailProps {
  detailOn: boolean;
  setDetailOn: (detailOn: boolean) => void;
  tid: string;
  serviceCode: string;
};

/* 거래내역조회 31 */
const menuId = 31;
export const AllTransactionDetail = ({
  detailOn,
  setDetailOn,
  tid,
  serviceCode
}: AllTransactionDetailProps) => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  
  const [amountInfo, setAmountInfo] = useState<AmountInfo>();
  const [importantInfo, setImportantInfo] = useState<ImportantInfo>();
  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>();
  const [transactionInfo, setTransactionInfo] = useState<TransactionInfo>();
  const [settlementInfo, setSettlementInfo] = useState<SettlementInfo>();
  const [partCancelInfo, setPartCancelInfo] = useState<PartCancelInfo>();
  const [showAmountInfo, setShowAmountInfo] = useState<boolean>(false);
  const [showPaymentInfo, setShowPaymentInfo] = useState<boolean>(false);
  const [showTransactionInfo, setShowTransactionInfo] = useState<boolean>(false);
  const [showSettlementInfo, setShowSettlementInfo] = useState<boolean>(false);
  const [showPartCancelInfo, setShowPartCancelInfo] = useState<boolean>(false);

  const { mutateAsync: allTransactionDetail } = useAllTransactionDetailMutation();
  
  const callDetail = () => {
    let allTransactionDetailParams: AllTransactionDetailParams = {
      serviceCode: serviceCode,
      tid: tid
    };
    allTransactionDetail(allTransactionDetailParams).then((rs: DetailResponse) => {
      setAmountInfo(rs.amountInfo);
      setImportantInfo(rs.importantInfo);
      setPaymentInfo(rs.paymentInfo);
      setTransactionInfo(rs.transactionInfo);
      setSettlementInfo(rs.settlementInfo);
      setPartCancelInfo(rs.partCancelInfo);
    }).catch((e: any) => {
      if(e.response?.data?.error?.message){
        snackBar(e.response?.data?.error?.message);
        return;
      }
    });
  };
  useEffect(() => {
    if(!!detailOn && serviceCode && tid){
      callDetail();
    }
  }, [detailOn]);

  const onClickToNavigate = (path: string) => {
    let timeout = setTimeout(() => {
      clearTimeout(timeout);
      navigate(PATHS.transaction.allTransaction.cancel, {
        state: {
          serviceCode: serviceCode,
          tid: tid
        }
      });
    }, 10);
  };

  const onClickToCancel = () => {
    if(checkGrant(menuId, 'X')){
      let msg = t('transaction.confirmCancel');

      overlay.open(({
        isOpen,
        close,
        unmount
      }) => {
        return (
          <Dialog
            afterLeave={ unmount }
            open={ isOpen }
            onClose={ close }
            onConfirmClick={ () => onClickToNavigate(PATHS.transaction.allTransaction.cancel) }
            // onConfirmClick={ () => callCancelInfo() }
            message={ msg }
            buttonLabel={[t('common.cancel'), t('common.confirm')]}
          />
        );
      });
    }
    else{
      showAlert(t('common.nopermission'));
    }
  };

  const onClickToClose = () => {
    setDetailOn(false);
  };

  const onClickToOpenInfo = (infoSectionKey: InfoSectionKeys) => {
    if(infoSectionKey === InfoSectionKeys.Amount){
      setShowAmountInfo(!showAmountInfo);
    }
    else if(infoSectionKey === InfoSectionKeys.Payment){
      setShowPaymentInfo(!showPaymentInfo);
    }
    else if(infoSectionKey === InfoSectionKeys.Transaction){
      setShowTransactionInfo(!showTransactionInfo);
    }
    else if(infoSectionKey === InfoSectionKeys.Settlement){
      setShowSettlementInfo(!showSettlementInfo);
    }
    else if(infoSectionKey === InfoSectionKeys.PartCancel){
      setShowPartCancelInfo(!showPartCancelInfo);
    }
  };

  return (
    <>
      <motion.div 
        className="full-menu-modal" 
        initial="hidden"
        animate={ (detailOn)? '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.detailTitle') }</div>
            <div className="full-menu-actions">
              <FullMenuClose
                addClass="full-menu-close"
                onClickToCallback={ onClickToClose }
              ></FullMenuClose>
            </div>
          </div>
          
          <div className="option-list pb-86">
            <div className="txn-detail">
              <AmountInfoSection
                transactionCategory={ TransactionCategory.AllTransaction }
                amountInfo={ amountInfo }
                isOpen={ showAmountInfo }
                tid={ tid } 
                serviceCode={ serviceCode }
                onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
              ></AmountInfoSection>
              <div className="txn-divider minus"></div>
              <ImportantInfoSection
                transactionCategory={ TransactionCategory.AllTransaction }
                importantInfo={ importantInfo }
                serviceCode={ serviceCode }
              ></ImportantInfoSection>
              { !!paymentInfo && 
                <>
                  <div className="txn-divider"></div>
                  <PaymentInfoSection
                    transactionCategory={ TransactionCategory.AllTransaction }
                    paymentInfo={ paymentInfo }
                    serviceCode={ serviceCode }
                    isOpen={ showPaymentInfo }
                    onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  ></PaymentInfoSection>
                </>
              }
              { !!transactionInfo &&
                <>
                  <div className="txn-divider"></div>
                  <TransactionInfoSection
                    transactionCategory={ TransactionCategory.AllTransaction }
                    transactionInfo={ transactionInfo }
                    serviceCode={ serviceCode }
                    isOpen={ showTransactionInfo }
                    onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  ></TransactionInfoSection>
                </>
              }
              { !!settlementInfo &&
                <>
                  <div className="txn-divider"></div>
                  <SettlementInfoSection
                    transactionCategory={ TransactionCategory.AllTransaction }
                    settlementInfo={ settlementInfo }
                    serviceCode={ serviceCode }
                    isOpen={ showSettlementInfo }
                    onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  ></SettlementInfoSection>
                </>
              }
              { !!partCancelInfo &&
                <>
                  <div className="txn-divider"></div>
                  <PartCancelInfoSection
                    transactionCategory={ TransactionCategory.AllTransaction }
                    partCancelInfo={ partCancelInfo }
                    serviceCode={ serviceCode }
                    isOpen={ showPartCancelInfo }
                    onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  ></PartCancelInfoSection>
                </>
              }
            </div>
          </div>
        </div>
        <div className="apply-row">
          <button
            className="btn-50 btn-blue flex-1"
            onClick={ () => onClickToCancel() }
          >{t('transaction.cancelTransaction')}</button>
        </div>
      </motion.div>
    </>
  );
};