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

export const PaymentInfoWrap = ({
  transactionCategory,
  paymentInfo,
  serviceCode,
  isOpen,
  onClickToOpenInfo
}: DetailInfoProps) => {

  const subItems: Record<string, Record<string, string>> = {
    approvalAcquire: {name: '승인매입', type: 'string'},
    approvalReturn: {name: '승인반송(횟수)', type: 'number'},
    approvalReAcquire: {name: '승인재매입(횟수)', type: 'number'},
    approvalVAN: {name: '승인VAN', type: 'string'},
    cancelAcquire: {name: '취소매입', type: 'string'},
    cancelReturn: {name: '취소반송', type: 'string'},
    cancelReAcquire: {name: '취소재매입', type: 'string'},
    acquireVAN: {name: '매입VAN', type: 'string'},
    acquireCompany: {name: '매입사(발급사)', type: 'string'},
    cardNumber: {name: '카드번호', type: 'string'},
    approvalNumber: {name: '승인번호', type: 'string'},
    installmentPeriod: {name: '할부기간', type: 'number'},
    authentication: {name: '인증', type: 'string'},
    accountType: {name: '유형', type: 'string'},
    bankName: {name: '은행명', type: 'string'},
    accountNumber: {name: '계좌번호', type: 'string'},
    depositBankName: {name: '입금금융기관명', type: 'string'},
    depositorName: {name: '입금자명', type: 'string'},
    depositDeadline: {name: '입금기한', type: 'date'},
    depositDate: {name: '입금일', type: 'date'},
    refundScheduleDate: {name: '환불예정일', type: 'date'},
    refundBankName: {name: '환불은행명', type: 'string'},
    refundAccountNumber: {name: '환불계좌번호', type: 'string'},
    accountHolder: {name: '예금주', type: 'string'},
    refundCompleteDate: {name: '환불완료일', type: 'date'},
    partner: {name: '제휴사', type: 'string'},
    cpid: {name: 'CPID', type: 'string'},
    productCategory: {name: '상품구분', type: 'string'},
    phoneNumber: {name: '휴대폰번호', type: 'string'},
    customerId: {name: '고객ID', type: 'string'},
    giftCardNumber: {name: '상품권번호', type: 'string'},
    culturelandId: {name: '컬처랜드ID', type: 'string'},
  };

  const openSubItems: Record<string, Array<string>> = {
    // 신용카드
    '01': ['approvalAcquire', 'approvalReturn', 'approvalReAcquire', 
      'approvalVAN', 'cancelAcquire', 'cancelReturn', 'cancelReAcquire',
      'acquireVAN', 'acquireCompany', 'cardNumber', 'approvalNumber',
      'installmentPeriod', 'authentication'],
    // 계좌이체
    '02': ['accountType', 'bankName', 'accountNumber'],
    // 가상계좌
    '03': ['bankName', 'accountNumber', 'depositBankName', 'depositorName',
      'depositDeadline', 'depositDate', 'refundScheduleDate',
      'refundBankName', 'refundAccountNumber', 'accountHolder'],
    // 휴대폰
    '04': ['refundCompleteDate', 'partner', 'cpid', 'productCategory', 'phoneNumber'],
    // 계좌간편결제
    '26': ['bankName', 'refundCompleteDate', 'accountHolder', 'accountType', 'customerId'],
    // SSG머니
    '21': ['giftCardNumber'],
    // SSG은행계좌
    '24': [],
    // 문화상품권
    '14': ['culturelandId'],
    // 티머니페이
    '31': ['cardNumber', 'approvalNumber', 'cpid'],
  };

  const checkValue = (val: any) => {
    return (!!val || val === 0);
  };
  let newPaymentInfo: Record<string, any> | undefined = paymentInfo;
  const subLi = () => {
    let rs = [];

    if(!!newPaymentInfo && !!serviceCode && !!openSubItems[serviceCode]){
      for(let i=0;i<openSubItems[serviceCode].length;i++){
        let k = openSubItems[serviceCode][i];
        if(!!k){
          rs.push(
            <li 
              key={`key-important-item-${i}`}
              className="kv-row"
            >
              <span className="k">·&nbsp;&nbsp;{ subItems[k]?.name }</span>
              <span className="v">
              { (checkValue(newPaymentInfo[k]) && subItems[k]?.type === 'string') &&
                newPaymentInfo[k] 
              }
              { (checkValue(newPaymentInfo[k]) && subItems[k]?.type === 'number') &&
                <NumericFormat
                  value={ newPaymentInfo[k] } 
                  thousandSeparator
                  displayType="text"
                  suffix='원'
                ></NumericFormat>
              }
              { (checkValue(newPaymentInfo[k]) && subItems[k]?.type === 'date') &&
                moment(newPaymentInfo[k]).format('YYYY.MM.DD')
              }
              </span>
            </li>
          );
        }
      }
    }
    return rs;
  };

  const onClickToSetOpenInfo = () => {
    if(!!onClickToOpenInfo){
      onClickToOpenInfo(InfoWrapKeys.Payment);
    }
  };
  
  return (
    <>
      <div className="txn-section">
        <div 
          className="section-title with-toggle"
          onClick={ () => onClickToSetOpenInfo() }
        >
          결제 정보 <SectionTitleArrow isOpen={ isOpen }></SectionTitleArrow>
        </div>
        <SlideDown className={'my-dropdown-slidedown'}>
        { !!isOpen &&
          <ul className="kv-list">
            { (transactionCategory === TransactionCategory.AllTransaction) && 
              subLi()
            }
            { (transactionCategory === TransactionCategory.Escrow) && 
              <>
                <li className="kv-row">
                  <span className="k">승인 금액</span>
                  <span className="v">
                    <NumericFormat
                      value={ paymentInfo?.paymentAmount } 
                      thousandSeparator
                      displayType="text"
                      suffix='원'
                    ></NumericFormat>
                  </span>
                </li>
                <li className="kv-row">
                  <span className="k">승인 번호</span>
                  <span className="v">{ paymentInfo?.approvalNumber }</span>
                </li>
              </>
            }
          </ul>
        }
        </SlideDown>
      </div>
    </>
  )
};