import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { AmountInfoWrap } from '@/entities/settlement/ui/info-wrap/amount-info-wrap';
import { SettlementInfoWrap } from '@/entities/settlement/ui/info-wrap/settlement-info-wrap';
import { TransactionInfoWrap } from '@/entities/settlement/ui/info-wrap/transaction-info-wrap'
import { 
  AmountInfo,
  InfoWrapKeys,
  SettlementInfo,
  SettlementPeriodType,
  SettlementsHistoryDetailParams,
  SettlementsHistoryDetailResponse,
  SettlementsTransactionDetailParams,
  SettlementsTransactionDetailResponse,
  TransactionInfo
} from '@/entities/settlement/model/types';
import { useSettlementsHistoryDetailMutation } from '@/entities/settlement/api/use-settlements-history-detail-mutation';
import { useSettlementsTransactionDetailMutation } from '@/entities/settlement/api/use-settlements-transaction-detail-mutation';
import { NumericFormat } from 'react-number-format';
import moment from 'moment';
import { useTranslation } from 'react-i18next';
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';
import { DetailMotionDuration, DetailMotionStyle, DetailMotionVariants } from '@/entities/common/model/constant';
import { snackBar } from '@/shared/lib';

export interface SettlementDetailProps {
  detailOn: boolean;
  setDetailOn: (detailOn: boolean) => void;
  periodType: SettlementPeriodType;
  settlementId?: string;
  tid?: string;
};

export const SettlementDetail = ({
  detailOn,
  setDetailOn,
  periodType,
  settlementId,
  tid
}: SettlementDetailProps) => {
  const { t, i18n } = useTranslation();
  
  const [amountInfo, setAmountInfo] = useState<AmountInfo>();
  const [settlementInfo, setSettlementInfo] = useState<SettlementInfo>();
  const [settlementAmount, setSettlementAmount] = useState<number>();
  const [settlementDate, setSettlementDate] = useState<string>();
  const [transactionInfo, setTransactionInfo] = useState<TransactionInfo>();
  const [transactionAmount, setTransactionAmount] = useState<number>();
  const [merchantName, setMerchantName] = useState<string>();

  const [showSettlement, setShowSettlement] = useState<boolean>(false);
  const [showTransaction, setShowTransaction] = useState<boolean>(false);

  const { mutateAsync: settlementsHistoryDetail } = useSettlementsHistoryDetailMutation();
  const { mutateAsync: settlementsTransactionDetail } = useSettlementsTransactionDetailMutation();
    
  const callSettlementDetail = () => {
    if(settlementId){
      let params: SettlementsHistoryDetailParams = {
        settlementId: settlementId
      };

      settlementsHistoryDetail(params).then((rs: SettlementsHistoryDetailResponse) => {
        if(rs.amountInfo){
          setAmountInfo(rs.amountInfo);
          setSettlementInfo(rs.settlementInfo);
          setSettlementAmount(rs.settlementAmount);
          setSettlementDate(rs.settlementDate);
        }
        else{
          snackBar('데이터가 존재하지 않습니다.');
          onClickToClose();
        }
      });
    }
  };

  const callTransactionDetail = () => {
    if(tid){
      let params: SettlementsTransactionDetailParams = {
        tid: tid
      };

      settlementsTransactionDetail(params).then((rs: SettlementsTransactionDetailResponse) => {
        setAmountInfo(rs.amountInfo);
        setTransactionInfo(rs.transactionInfo);
        setTransactionAmount(rs.transactionAmount);
        setMerchantName(rs.merchantName);
      });
    }
  };
  
  const onClickToShowInfo = (infoWrapKey: InfoWrapKeys) => {
    if(infoWrapKey === InfoWrapKeys.Settlement){
      setShowSettlement(!showSettlement);
    }
    else if(infoWrapKey === InfoWrapKeys.Transaction){
      setShowTransaction(!showTransaction);
    }
  };

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

  useEffect(() => {
    if(periodType === SettlementPeriodType.SETTLEMENT_DATE && settlementId){
      callSettlementDetail();
    }
    else if(periodType === SettlementPeriodType.TRANSACTION_DATE && tid){
      callTransactionDetail();
    }
  }, [periodType, settlementId, tid]);

  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('settlement.detailTitle') }</div>
            <div className="full-menu-actions">
              <FullMenuClose
                addClass="full-menu-close"
                onClickToCallback={ onClickToClose }
              ></FullMenuClose>
            </div>
          </div>
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className="txn-detail">
                { (periodType === SettlementPeriodType.SETTLEMENT_DATE) &&
                  <div className="txn-num-group">
                    <div className="txn-amount">
                      <div className="value">
                        {i18n.language === 'en' && <span className="unit">{t('home.currencySymbol')}</span>}
                        <NumericFormat
                          value={ settlementAmount }
                          thousandSeparator
                          displayType="text"
                        ></NumericFormat>
                        {i18n.language !== 'en' && <span className="unit">{t('home.currencyWon')}</span>}
                      </div>
                    </div>
                    <div className="txn-date">{ moment(settlementDate).format('YYYY.MM.DD') }</div>
                  </div>
                }
                { (periodType === SettlementPeriodType.TRANSACTION_DATE) &&
                  <div className="txn-num-group">
                    <div className="txn-amount">
                      <div className="value">
                        {i18n.language === 'en' && <span className="unit">{t('home.currencySymbol')}</span>}
                        <NumericFormat
                          value={ transactionAmount }
                          thousandSeparator
                          displayType="text"
                        ></NumericFormat>
                        {i18n.language !== 'en' && <span className="unit">{t('home.currencyWon')}</span>}
                      </div>
                    </div>
                    <div className="txn-date">{ merchantName }</div>
                  </div>
                }
                <div className="txn-divider minus"></div>
                
                <AmountInfoWrap
                  periodType={ periodType }
                  amountInfo={ amountInfo }
                  settlementAmount={ settlementAmount }
                ></AmountInfoWrap>
                <div className="txn-divider"></div>
                { (periodType === SettlementPeriodType.SETTLEMENT_DATE) && 
                  <SettlementInfoWrap
                    settlementInfo={ settlementInfo }
                    isOpen={ showSettlement }
                    onClickToShowInfo={ (infoWrapKey) => onClickToShowInfo(infoWrapKey) }
                  ></SettlementInfoWrap>
                }
                { (periodType === SettlementPeriodType.TRANSACTION_DATE) && 
                  <TransactionInfoWrap
                    transactionInfo={ transactionInfo }
                    isOpen={ showTransaction }
                    onClickToShowInfo={ (infoWrapKey) => onClickToShowInfo(infoWrapKey) }
                  ></TransactionInfoWrap>
                }
              </div>
            </div>
          </div>
        </div>
      </motion.div>
    </>
  );
};