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

export const AmountInfoWrap = ({
  transactionCategory, 
  amountInfo,
  isOpen,
  tid,
  serviceCode,
  onClickToOpenInfo
}: DetailInfoProps) => {
  const { mutateAsync: downloadConfirmation } = useDownloadConfirmationMutation();

  const subItems: Record<string, Record<string, string>> = {
    mid: {name: 'MID', type: 'string'}, 
    amount: {name: '거래금액', type: 'number'},
    cardAmount: {name: '신용카드금액', type: 'number'},
    pointAmount: {name: '포인트금액', type: 'number'},
    couponAmount: {name: '쿠폰금액', type: 'number'},
    kakaoMoney: {name: '카카오머니', type: 'number'},
    kakaoPoint: {name: '카카오포인트', type: 'number'},
    kakaoInstantDiscount: {name: '카카오 즉시할인', type: 'number'},
    naverPoint: {name: '네이버 포인트', type: 'number'},
    tossMoney: {name: '토스머니', type: 'number'}, 
    tossDiscount: {name: '토스할인', type: 'number'},
    paycoPoint: {name: '페이코 포인트', type: 'number'},
    paycoCoupon: {name: '페이코 쿠폰', type: 'number'},
    escrowFee: {name: '에스크로수수료', type: 'number'}
  };
  
  const showTop = ['01', '02', '03', '26'];
  const openSubItems: Record<string, Array<string>> = {
    // 신용카드
    '01': ['mid', 'cardAmount', 'pointAmount', 
      'couponAmount', 'escrowFee', 'kakaoMoney',
      'kakaoPoint', 'kakaoInstantDiscount', 'naverPoint',
      'tossMoney', 'tossDiscount', 'paycoPoint', 'paycoCoupon'
    ],
    // 계좌이체
    '02': ['amount', 'mid', 'escrowFee'],
    // 가상계좌
    '03': ['amount', 'mid'],
    // 휴대폰
    '04': ['amount', 'mid'],
    // 계좌간편결제
    '26': ['amount', 'mid', 'escrowFee'],
    // SSG머니
    '21': ['amount', 'mid'],
    // SSG은행계좌
    '24': ['amount', 'mid'],
    // 문화상품권
    '14': ['amount', 'mid'],
    // 티머니페이
    '31': ['amount', 'mid'],
  };
  
  const checkValue = (val: any) => {
    return (!!val || val === 0);
  };
  let newAmountInfo: Record<string, any> | undefined = amountInfo;
  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){
          rs.push(
            <li 
              key={`key-amount-item-${i}`}
              className="amount-item"
            >
              <span className="label">·&nbsp;&nbsp;{ subItems[k]?.name }</span>
              <span className="value">
              { (checkValue(newAmountInfo[k]) && subItems[k]?.type === 'string') &&
                newAmountInfo[k] 
              }
              { (checkValue(newAmountInfo[k]) && subItems[k]?.type === 'number') &&
                <NumericFormat
                  value={ newAmountInfo[k] } 
                  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(InfoWrapKeys.Amount);
    }
  };

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

  return (
    <>
      <div className="txn-num-group">
        <div className="txn-amount">
          <div className="value">
            <NumericFormat
              value={ amountInfo?.amount } 
              thousandSeparator
              displayType="text"
            ></NumericFormat>
            <span className="unit">원</span>
          </div>
          <button 
            className="chip-btn" 
            type="button"
            onClick={ () => onClickToSetShowInfo() }
          >
            금액상세 <SectionTitleArrow isOpen={ isOpen }></SectionTitleArrow>
          </button>
        </div>

        <SlideDown className={'my-dropdown-slidedown'}>
        { !!isOpen &&
          <div className="amount-expand">
            <ul className="amount-list">
              { subLi() }
            </ul>
          </div>
        }
        </SlideDown>
        <div className="txn-mid">
          <span className="value">{ amountInfo?.mid }</span>
        </div>
        <div className="txn-doc">
          <button 
            className="doc-btn" 
            type="button"
            onClick={ () => onClickToDownloadConfirmation() }
          >거래 확인서</button>
        </div>
      </div>
    </>
  );
};