import moment from 'moment';
import { useTranslation } from 'react-i18next';
import { NumericFormat } from 'react-number-format';
import { SectionTitleArrow } from '@/entities/common/ui/section-title-arrow';
import { useDownloadConfirmationMutation } from '../../api/use-download-confirmation-mutation';
import { InfoSectionKeys, InfoSectionProps, TransactionCategory } from '../../model/types';
import { SlideDown } from 'react-slidedown';
import 'react-slidedown/lib/slidedown.css';

export const AmountInfoSection = ({
  transactionCategory,
  amountInfo,
  isOpen,
  tid,
  serviceCode,
  onClickToOpenInfo,
  canDownloadReceipt
}: InfoSectionProps) => {
  const { t } = useTranslation();
  const { mutateAsync: downloadConfirmation } = useDownloadConfirmationMutation();
  let newAmountInfo: Record<string, any> | undefined = amountInfo;
  const subItems: Record<string, Record<string, string>> = {
    mid: {name: t('transaction.fields.mid'), type: 'string'},
    transactionRequestAmount: {name: t('transaction.fields.transactionRequestAmount'), type: 'number'},
    transactionAmount: {name: t('transaction.fields.transactionAmount'), type: 'number'},
    pointAmount: {name: t('transaction.fields.pointAmount'), type: 'number'},
    couponAmount: {name: t('transaction.fields.couponAmount'), type: 'number'},
    escrowFee: {name: t('transaction.fields.escrowFee'), type: 'number'},
    kakaoMoneyAmount: {name: t('transaction.fields.kakaoMoneyAmount'), type: 'number'},
    kakaoPointAmount: {name: t('transaction.fields.kakaoPointAmount'), type: 'number'},
    kakaoDiscountAmount: {name: t('transaction.fields.kakaoDiscountAmount'), type: 'number'},
    naverPointAmount: {name: t('transaction.fields.naverPointAmount'), type: 'number'},
    tossMoneyAmount: {name: t('transaction.fields.tossMoneyAmount'), type: 'number'},
    tossDiscountAmount: {name: t('transaction.fields.tossDiscountAmount'), type: 'number'},
    paycoPointAmount: {name: t('transaction.fields.paycoPointAmount'), type: 'number'},
    paycoCouponAmount: {name: t('transaction.fields.paycoCouponAmount'), type: 'number'},
  };
 
  const openSubItems: Record<string, Array<string>> = {
    // 신용카드
    '01': ['transactionAmount', 'pointAmount', 'couponAmount', 'escrowFee'],
    // 계좌이체
    '02': ['mid', 'transactionRequestAmount', 'transactionAmount', 'escrowFee'],
    // 가상계좌
    '03': ['mid', 'transactionRequestAmount', 'transactionAmount'],
    // 휴대폰
    '05': ['mid', 'transactionRequestAmount', 'transactionAmount'],
    // 문화상품권
    '14': ['mid', 'transactionAmount'],
    // SSG머니
    '21': ['mid', 'transactionAmount'],
    // SSG은행계좌
    '24': ['mid', 'transactionAmount'],
    // 계좌간편결제
    '26': ['mid', 'transactionAmount', 'escrowFee'],
    // 티머니페이
    '31': ['mid', 'transactionAmount'],
  };
  if(newAmountInfo?.partServiceCode === 'E015'){
    openSubItems['01']?.push('paycoPointAmount');
    openSubItems['01']?.push('paycoCouponAmount');
  }
  else if(newAmountInfo?.partServiceCode === 'E016'){
    openSubItems['01']?.push('kakaoMoneyAmount');
    openSubItems['01']?.push('kakaoPointAmount');
    openSubItems['01']?.push('kakaoDiscountAmount');
  }
  else if(newAmountInfo?.partServiceCode === 'E020'){
    openSubItems['01']?.push('naverPointAmount');
  }
  else if(newAmountInfo?.partServiceCode === 'E025'){
    openSubItems['01']?.push('tossMoneyAmount');
    openSubItems['01']?.push('tossDiscountAmount');
  }
  
  
  const checkValue = (val: any) => {
    return (!!val || val === 0);
  };

  const getAmountValue = (k?: string) => {
    let value = 0;
    let rs = [];
    if(!!k){
      let value = 0;
      if(k === 'kakaoMoneyAmount'
        && newAmountInfo?.partServiceCode === 'E016'
      ){
        value = newAmountInfo['multiPointAmount'] || 0;
      }
      else if(k === 'kakaoPointAmount'
        && newAmountInfo?.partServiceCode === 'E016'
      ){
        value = newAmountInfo['multiCouponAmount'] || 0;
      }
      else if(k === 'naverPointAmount'
        && newAmountInfo?.partServiceCode === 'E020'
      ){
        value = newAmountInfo['multiPointAmount'] || 0;
      }
      else if(k === 'tossMoneyAmount'
        && newAmountInfo?.partServiceCode === 'E025'
      ){
        value = newAmountInfo['multiPointAmount'] || 0;
      }
      else if(k === 'paycoPointAmount'
        && newAmountInfo?.partServiceCode === 'E015'
      ){
        value = newAmountInfo['multiPointAmount'] || 0;
      }
      else if(k === 'paycoCouponAmount'
        && newAmountInfo?.partServiceCode === 'E015'
      ){
        value = newAmountInfo['multiCouponAmount'] || 0;
      }
      else{
        if(newAmountInfo){
          value = newAmountInfo[k] || 0;
        }
      }
      rs.push(
        <NumericFormat
          value={ value } 
          thousandSeparator
          displayType="text"
        ></NumericFormat>
      )
    }
    return rs; 
  };
  
  const subLi = () => {
    let rs = [];
    if(!!newAmountInfo && !!serviceCode && !!openSubItems[serviceCode]){
      for(let i=0;i<openSubItems[serviceCode].length;i++){
        let k = openSubItems[serviceCode][i];
        if(!!k){
          let name = subItems[k]?.name;


          if(serviceCode === '01'){
            if(k === 'transactionAmount'){
              name = t('transaction.fields.cardAmount')
            }
            if(k === 'transactionRequestAmount'){
              name = t('transaction.fields.approvalRequestAmount');
            }
          }
          
          rs.push(
            <li 
              key={`key-amount-item-${i}`}
              className="amount-item"
            >
              <span className="label">·&nbsp;&nbsp;{ name }</span>
              <span className="value">
              { (checkValue(newAmountInfo[k]) && subItems[k]?.type === 'string') &&
                newAmountInfo[k] 
              }
              { (subItems[k]?.type === 'number') && 
                getAmountValue(k)
                /*
                <NumericFormat
                  value={ newAmountInfo[k] || 0 } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat>
                */
              }
              { (checkValue(newAmountInfo[k]) && subItems[k]?.type === 'date') &&
                moment(newAmountInfo[k]).format('YYYY.MM.DD')
              }
              </span>
            </li>
          );
        }
      }
    }
    return rs;
  }
    
  const onClickToSetShowInfo = () => {
    if(!!onClickToOpenInfo){
      onClickToOpenInfo(InfoSectionKeys.Amount);
    }
  };

  const onClickToDownloadConfirmation = () => {
    if(!!tid){
      downloadConfirmation({
        tid: tid
      }).then((rs) => {
        alert('거래확인서 다운 성공');
      });
    }
  };

  return (
    <>
      <div className="txn-num-group">
        <div className="txn-amount">
          <div className="value">
            { (transactionCategory === TransactionCategory.AllTransaction) &&
              (serviceCode === '01' || serviceCode === '02' || serviceCode === '03' || serviceCode === '26') &&
              <NumericFormat
                value={ amountInfo?.transactionRequestAmount } 
                thousandSeparator
                displayType="text"
              ></NumericFormat>
            }
            { (transactionCategory === TransactionCategory.AllTransaction) &&
              (serviceCode === '05' || serviceCode === '14' || serviceCode === '21' 
                || serviceCode === '24' || serviceCode === '31') &&
              <NumericFormat
                value={ amountInfo?.transactionAmount} 
                thousandSeparator
                displayType="text"
              ></NumericFormat> 
            }
            { (transactionCategory === TransactionCategory.CashReceipt) &&
              <NumericFormat
                value={ amountInfo?.amount } 
                thousandSeparator
                displayType="text"
              ></NumericFormat> 
            }
            { (transactionCategory === TransactionCategory.Escrow) &&
              <NumericFormat
                value={ amountInfo?.approvalRequestAmount } 
                thousandSeparator
                displayType="text"
              ></NumericFormat> 
            }
            { (transactionCategory === TransactionCategory.Billing) &&
              <NumericFormat
                value={ amountInfo?.transactionAmount } 
                thousandSeparator
                displayType="text"
              ></NumericFormat> 
            }
            <span className="unit">원</span>
          </div>
          <button
            className="chip-btn"
            type="button"
            onClick={ () => onClickToSetShowInfo() }
          >
            {t('transaction.sections.amountDetail')} <SectionTitleArrow isOpen={ isOpen }></SectionTitleArrow>
          </button>
        </div>

        <SlideDown className={'my-dropdown-slidedown'}>
        { !!isOpen &&
          <div className="amount-expand">
            <ul className="amount-list">
              { (transactionCategory === TransactionCategory.AllTransaction) && 
                subLi() 
              }
              { (transactionCategory === TransactionCategory.CashReceipt) &&
                <>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.supplyAmount')}</span>
                    <span className="value">
                      <NumericFormat
                        value={ amountInfo?.supplyAmount || 0 }
                        thousandSeparator
                        displayType="text"
                      ></NumericFormat>
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.vat')}</span>
                    <span className="value">
                      <NumericFormat
                        value={ amountInfo?.vat || 0 }
                        thousandSeparator
                        displayType="text"
                      ></NumericFormat>
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.serviceAmount')}</span>
                    <span className="value">
                      <NumericFormat
                        value={ amountInfo?.serviceAmount || 0 }
                        thousandSeparator
                        displayType="text"
                      ></NumericFormat>
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.taxFreeAmount')}</span>
                    <span className="value">
                      <NumericFormat
                        value={ amountInfo?.taxFreeAmount || 0 }
                        thousandSeparator
                        displayType="text"
                      ></NumericFormat>
                    </span>
                  </li>
                </>
              }
              { (transactionCategory === TransactionCategory.Escrow) &&
                <>
                  { (serviceCode === '02' || serviceCode === '03') &&
                    <li className="amount-item">
                      <span className="label">·&nbsp;&nbsp;{t('transaction.fields.transactionAmount')}</span>
                      <span className="value">
                        <NumericFormat
                          value={ amountInfo?.transactionAmount || 0 }
                          thousandSeparator
                          displayType="text"
                        ></NumericFormat>
                      </span>
                    </li>
                  }
                  { (serviceCode === '01') &&
                    <>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.cardAmount')}</span>
                        <span className="value">
                          <NumericFormat
                            value={ amountInfo?.cardAmount || 0}
                            thousandSeparator
                            displayType="text"
                          ></NumericFormat>
                        </span>
                      </li>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.pointAmount')}</span>
                        <span className="value">
                          <NumericFormat
                            value={ amountInfo?.pointAmount || 0 }
                            thousandSeparator
                            displayType="text"
                          ></NumericFormat>
                        </span>
                      </li>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.couponAmount')}</span>
                        <span className="value">
                          <NumericFormat
                            value={ amountInfo?.couponAmount || 0 }
                            thousandSeparator
                            displayType="text"
                          ></NumericFormat>
                        </span>
                      </li>
                    </>
                  }
                  { (serviceCode === '01' || serviceCode === '02') &&
                    <li className="amount-item">
                      <span className="label">·&nbsp;&nbsp;{t('transaction.fields.escrowFee')}</span>
                      <span className="value">
                        <NumericFormat
                          value={ amountInfo?.escrowFee || 0 }
                          thousandSeparator
                          displayType="text"
                        ></NumericFormat>
                      </span>
                    </li>
                  }
                  { (serviceCode === '01') &&
                    <>
                      { (amountInfo?.simplePaymentServiceCode === 'E016') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoMoneyAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.multiPointAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoPointAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.multiCouponAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoDiscountAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.kakaoDiscountAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                        </>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E020') &&
                        <li className="amount-item">
                          <span className="label">·&nbsp;&nbsp;{t('transaction.fields.naverPointAmount')}</span>
                          <span className="value">
                            <NumericFormat
                              value={ amountInfo?.multiPointAmount || 0 }
                              thousandSeparator
                              displayType="text"
                            ></NumericFormat>
                          </span>
                        </li>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E025') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.tossMoneyAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.multiPointAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.tossDiscountAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.tossDiscountAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                        </>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E015') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.paycoPointAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.multiPointAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.paycoCouponAmount')}</span>
                            <span className="value">
                              <NumericFormat
                                value={ amountInfo?.multiCouponAmount || 0 }
                                thousandSeparator
                                displayType="text"
                              ></NumericFormat>
                            </span>
                          </li>
                        </>
                      }
                    </>
                  }
                </>
              } 
            </ul>
          </div>
        }
        </SlideDown>
        { ((transactionCategory === TransactionCategory.AllTransaction) ||
          (transactionCategory === TransactionCategory.Escrow)) &&
          <div className="txn-mid">
            <span className="value">{ amountInfo?.mid }</span>
          </div>
        }
        { (transactionCategory === TransactionCategory.CashReceipt) &&
          <div className="txn-mid">
            <span className="value">{ amountInfo?.customerName }</span>
          </div>
        }
        <div className="txn-doc">
          {
            (transactionCategory === TransactionCategory.CashReceipt) &&
            !!canDownloadReceipt &&
            <button
              className="doc-btn"
              type="button"
              onClick={ () => onClickToDownloadConfirmation() }
            >{t('transaction.fields.transactionConfirmation')}</button>
          }
        </div>
      </div>
    </>
  );
};