import moment from 'moment';
import { useTranslation } from 'react-i18next';
import { SectionTitleArrow } from '@/entities/common/ui/section-title-arrow';
import { AmountInfo, CashReceiptReceiptDownloadParams, CashReceiptReceiptDownloadResponse, CashReceiptReceiptSendEmailParams, CashReceiptReceiptSendEmailResponse, CustomerInfo, InfoSectionKeys, InfoSectionProps, IssueInfo, MerchantInfo, ProductInfo, TransactionCategory, TransactionInfo } from '../../model/types';
import { SlideDown } from 'react-slidedown';
import 'react-slidedown/lib/slidedown.css';
import { snackBar } from '@/shared/lib';
import { useCashReceiptReceiptDownloadMutation } from '../../api/use-cash-receipt-receipt-download-mutation';
import { useState } from 'react';
import { DownloadBottomSheet, DownloadSelectedMode } from '@/entities/common/ui/download-bottom-sheet';
import { CashReceiptSample } from '@/entities/common/ui/cash-receipt-sample';
import { useCashReceiptReceiptSendEmailMutation } from '../../api/use-cash-receipt-receipt-send-email-mutation';
import { useDownloadBottomSheetOnStore } from '@/shared/model/store';

export const AmountInfoSection = ({
  transactionCategory,
  amountInfo,
  isOpen,
  tid,
  serviceCode,
  onClickToOpenInfo,
  canDownloadReceipt
}: InfoSectionProps) => {
  const { t } = useTranslation();

  const { mutateAsync: cashReceiptReceiptDownload } = useCashReceiptReceiptDownloadMutation();
  const { mutateAsync: cashReceiptReceiptSendEamil } = useCashReceiptReceiptSendEmailMutation();

  const { downloadBottomSheetOn, setDownloadBottomSheetOn } = useDownloadBottomSheetOnStore();
  const [cashReceiptSampleOn, setCashReceiptSampleOn] = useState<boolean>(false);

  const [receiptIssueInfo, setReceiptIssueInfo] = useState<IssueInfo>({});
  const [receiptMerchantInfo, setReceiptMerchantInfo] = useState<MerchantInfo>({});
  const [receiptTransactionInfo, setReceiptTransactionInfo] = useState<TransactionInfo>({});
  const [receiptAmountInfo, setReceiptAmountInfo] = useState<AmountInfo>({});
  const [receiptCustomerInfo, setReceiptCustomerInfo] = useState<CustomerInfo>();
  const [receiptProductInfo, setReceiptProductInfo] = useState<ProductInfo>();

  let newAmountInfo: Record<string, any> | undefined = amountInfo;
  const subItems: Record<string, Record<string, 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': ['transactionRequestAmount', 'transactionAmount', 'escrowFee'],
    // 가상계좌
    '03': ['transactionRequestAmount', 'transactionAmount'],
    // 휴대폰
    '05': ['transactionRequestAmount', 'transactionAmount'],
    // 문화상품권
    '14': ['transactionAmount'],
    // SSG머니
    '21': ['transactionAmount'],
    // SSG은행계좌
    '24': ['transactionAmount'],
    // 계좌간편결제
    '26': ['transactionAmount', 'escrowFee'],
    // 티머니페이
    '31': ['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(
        t('home.money', { value: new Intl.NumberFormat('en-US').format(value || 0) })
      )
    }
    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 onClickToOpenDownloadBottomSheet = () => {
    setDownloadBottomSheetOn(true);
  };

  const onRequestDownload = (
		selectedMode: DownloadSelectedMode,
		userEmail?: string
	) => {
    if(!!tid){
      if(selectedMode === DownloadSelectedMode.EMAIL
        && !!userEmail
      ){
        let params: CashReceiptReceiptSendEmailParams = {
          tid: tid,
          email: userEmail
        };
        cashReceiptReceiptSendEamil(params).then((rs: CashReceiptReceiptSendEmailResponse) => {
          console.log(rs);
          if(rs.message){
            snackBar(rs.message);
          }
        }).catch((e: any) => {
          if(e.response?.data?.error?.message){
            snackBar(e.response?.data?.error?.message);
            return;
          }
        });
      }
      else if(selectedMode === DownloadSelectedMode.IMAGE){
        let params: CashReceiptReceiptDownloadParams = {
          tid: tid
        };
        cashReceiptReceiptDownload(params).then((rs: CashReceiptReceiptDownloadResponse) => {
          /*
          if(rs?.merchantInfo){
            rs.merchantInfo.merchantName = '나이스페이먼츠';
          }
          */
          setReceiptIssueInfo(rs?.issueInfo);
          setReceiptMerchantInfo(rs?.merchantInfo);
          setReceiptTransactionInfo(rs?.transactionInfo);
          setReceiptAmountInfo(rs?.amountInfo);
          setReceiptCustomerInfo(rs?.customerInfo);
          setReceiptProductInfo(rs?.productInfo);
          setCashReceiptSampleOn(true);
          
        }).catch((e: any) => {
          if(e.response?.data?.error?.message){
            snackBar(e.response?.data?.error?.message);
            return;
          }
        });
      }
    }
  };
  
  return (
    <>
      <div className="txn-num-group">
        <div className="txn-amount">
          <div className="value">
            { (transactionCategory === TransactionCategory.AllTransaction) &&
              (serviceCode === '01' || serviceCode === '02' || serviceCode === '03' || serviceCode === '26') &&
              t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.transactionRequestAmount || 0) })
            }
            { (transactionCategory === TransactionCategory.AllTransaction) &&
              (serviceCode === '05' || serviceCode === '14' || serviceCode === '21'
                || serviceCode === '24' || serviceCode === '31') &&
              t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.transactionAmount || 0) })
            }
            { (transactionCategory === TransactionCategory.CashReceipt) &&
              t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.amount || 0) })
            }
            { (transactionCategory === TransactionCategory.Escrow) &&
              t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.approvalRequestAmount || 0) })
            }
            { (transactionCategory === TransactionCategory.Billing) &&
              t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.transactionAmount || 0) })
            }
          </div>
          { (transactionCategory === TransactionCategory.AllTransaction) &&
            (serviceCode === '01' || serviceCode === '02' || serviceCode === '03' || serviceCode === '26') &&
            <button
              className="chip-btn"
              type="button"
              onClick={ () => onClickToSetShowInfo() }
            >
              {t('transaction.sections.amountDetail')} <SectionTitleArrow isOpen={ isOpen }></SectionTitleArrow>
            </button>
          }
          { ((transactionCategory === TransactionCategory.CashReceipt) ||
            (transactionCategory === TransactionCategory.Escrow) ||
            (transactionCategory === TransactionCategory.Billing)) &&
            <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">
                      {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.supplyAmount || 0) })}
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.vat')}</span>
                    <span className="value">
                      {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.vat || 0) })}
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.serviceAmount')}</span>
                    <span className="value">
                      {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.serviceAmount || 0) })}
                    </span>
                  </li>
                  <li className="amount-item">
                    <span className="label">·&nbsp;&nbsp;{t('transaction.fields.taxFreeAmount')}</span>
                    <span className="value">
                      {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.taxFreeAmount || 0) })}
                    </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">
                        {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.transactionAmount || 0) })}
                      </span>
                    </li>
                  }
                  { (serviceCode === '01') &&
                    <>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.cardAmount')}</span>
                        <span className="value">
                          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.cardAmount || 0) })}
                        </span>
                      </li>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.pointAmount')}</span>
                        <span className="value">
                          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.pointAmount || 0) })}
                        </span>
                      </li>
                      <li className="amount-item">
                        <span className="label">·&nbsp;&nbsp;{t('transaction.fields.couponAmount')}</span>
                        <span className="value">
                          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.couponAmount || 0) })}
                        </span>
                      </li>
                    </>
                  }
                  { (serviceCode === '01' || serviceCode === '02') &&
                    <li className="amount-item">
                      <span className="label">·&nbsp;&nbsp;{t('transaction.fields.escrowFee')}</span>
                      <span className="value">
                        {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.escrowFee || 0) })}
                      </span>
                    </li>
                  }
                  { (serviceCode === '01') &&
                    <>
                      { (amountInfo?.simplePaymentServiceCode === 'E016') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoMoneyAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiPointAmount || 0) })}
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoPointAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiCouponAmount || 0) })}
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.kakaoDiscountAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.kakaoDiscountAmount || 0) })}
                            </span>
                          </li>
                        </>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E020') &&
                        <li className="amount-item">
                          <span className="label">·&nbsp;&nbsp;{t('transaction.fields.naverPointAmount')}</span>
                          <span className="value">
                            {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiPointAmount || 0) })}
                          </span>
                        </li>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E025') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.tossMoneyAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiPointAmount || 0) })}
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.tossDiscountAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.tossDiscountAmount || 0) })}
                            </span>
                          </li>
                        </>
                      }
                      { (amountInfo?.simplePaymentServiceCode === 'E015') &&
                        <>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.paycoPointAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiPointAmount || 0) })}
                            </span>
                          </li>
                          <li className="amount-item">
                            <span className="label">·&nbsp;&nbsp;{t('transaction.fields.paycoCouponAmount')}</span>
                            <span className="value">
                              {t('home.money', { value: new Intl.NumberFormat('en-US').format(amountInfo?.multiCouponAmount || 0) })}
                            </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={ () => onClickToOpenDownloadBottomSheet() }
            >{t('transaction.fields.transactionConfirmation')}</button>
          }
        </div>
      </div>
      { !!downloadBottomSheetOn &&
        <DownloadBottomSheet
          bottomSheetOn={ downloadBottomSheetOn }
          setBottomSheetOn={ setDownloadBottomSheetOn }
          imageMode={ true }
          emailMode={ true }
          sendRequest={ onRequestDownload }
        ></DownloadBottomSheet>
      }
      { !!cashReceiptSampleOn &&
        <CashReceiptSample
          cashReceiptSampleOn={ cashReceiptSampleOn }
          setCashReceiptSampleOn={ setCashReceiptSampleOn }
          merchantInfo={ receiptMerchantInfo }
          issueInfo={ receiptIssueInfo }
          amountInfo={ receiptAmountInfo }
          transactionInfo={ receiptTransactionInfo }
          customerInfo={ receiptCustomerInfo }
          productInfo={ receiptProductInfo }
        ></CashReceiptSample>
      }
    </>
  );
};