import { NumericFormat } from 'react-number-format';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { ListItemProps, TransactionCategory } from '../model/types';
import moment from 'moment';
import { useStore } from '@/shared/model/store';
import { AllTracsactionStatusCode } from '../model/contant';

export const ListItem = ({
  transactionCategory,
  tid, mid, statusCode,
  installmentMonth, serviceName, serviceCode,
  serviceDetailName, goodsAmount,
  id, amount, customerName, issueNumber,
  issueStatus, paymentMethod, processResult, 
  transactionDateTime, transactionAmount,
  deliveryStatus, settlementStatus, 
  cancelStatus, billKey, orderNumber
}: ListItemProps) => {
  const { navigate } = useNavigate();
  const getItemClass = () => {
    let rs = '';
    if(statusCode === '0'){
      rs = '';
    }
    else if(statusCode === '1'){
      rs = 'approved';
    }
    else if(statusCode === '2'){
      rs = 'refund';
    }
    return rs;
  };

  const getDotClass = (str?: string) => {
    let rs = '';
    if(statusCode === '0'){
      rs = '';
    }
    else if(statusCode === '1'){
      rs = 'blue';
    }
    else if(statusCode === '2'){
      rs = 'gray';
    }
    return rs;
  };

  const onClickToNavigate = () => {
    if(transactionCategory === TransactionCategory.AllTransaction){
      navigate(PATHS.transaction.allTransaction.detail, {
        state: {
          tid: tid,
          serviceCode: serviceCode
        }
      });
    }
    else if(transactionCategory === TransactionCategory.CashReceipt){
      navigate(PATHS.transaction.cashReceipt.detail, {
        state: {
          issueNumber: issueNumber
        }
      });
    }
    else if(transactionCategory === TransactionCategory.Escrow){
      navigate(PATHS.transaction.escrow.detail, {
        state: {
          issueNumber: issueNumber
        }
      });
    }
    else if(transactionCategory === TransactionCategory.Billing){
      navigate(PATHS.transaction.billing.detail, {
        state: {
          billKey: billKey
        }
      });
    }
    else{
      alert('pageType 이 존재하지 않습니다.');
    }
  };
  
  const getTime = () => {
    let timeStr = '';
    if(transactionCategory === TransactionCategory.AllTransaction){
      let time = transactionDateTime?.substring(8, 12);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4);
    }
    else{
      timeStr = moment(transactionDateTime).format('HH:mm');
    }
    return timeStr
  };

  const getTitle = () => {
    let str = '';
    if(transactionCategory === TransactionCategory.AllTransaction){
      let strDetailName = '';
      if(serviceDetailName){
        strDetailName = serviceDetailName?.split('|').join(',');
      }
      if(strDetailName){
        let last = strDetailName.slice(-1);
        if(last === ','){
          strDetailName = strDetailName.substring(0, strDetailName.length - 1);
        }
        str = `${serviceName}(${strDetailName})`;
      }
      else{
        str = `${serviceName}`;
      }
    }
    else if(transactionCategory === TransactionCategory.CashReceipt){
      str = `${customerName}(${issueNumber})`
    }
    else if(transactionCategory === TransactionCategory.Escrow){
      str = `${customerName}(${issueNumber})`
    }
    else if(transactionCategory === TransactionCategory.Billing){
      str = `${billKey}`
    }
    return str;
  };

  const getStatusName = () => {
    let str;
    if(transactionCategory === TransactionCategory.AllTransaction){
      Loop1: 
      for(let i=0;i<AllTracsactionStatusCode.length;i++){
        if(serviceCode === AllTracsactionStatusCode[i]?.serviceCode){
          let list = AllTracsactionStatusCode[i]?.list;
          if(!!list){
            Loop2:
            for(let j=0;j<list.length;j++){
              if(list[j]?.code === statusCode){
                str = list[j]?.ko;
                break Loop1;
              }
            }
          }
        }
      }
    }
    return str || '';
  };

  const getDetail = () => {
    let rs = [];
    if(transactionCategory === TransactionCategory.AllTransaction){
      rs.push(
        <div 
          className="transaction-details"
          key={ tid }
        >
          <span>{ getTime() }</span>
          <span className="separator">|</span>
          <span>{ getStatusName() }</span>
          <span className="separator">|</span>
          <span>{ mid }</span>
          {
            (!!installmentMonth && parseInt(installmentMonth) > 1) && 
              <>
                <span className="separator">|</span>
                <span>{ installmentMonth }개월 할부</span>
              </>
          }
        </div>
      );
    }
    else if(transactionCategory === TransactionCategory.CashReceipt){
      rs.push(
        <div className="transaction-details">
          <span>{ getTime() }</span>
          <span className="separator">|</span>
          <span>{ issueStatus }</span>
          <span className="separator">|</span>
          <span>{ paymentMethod }</span>
          <span className="separator">|</span>
          <span>{ processResult }</span>
        </div>
      );
    }
    else if(transactionCategory === TransactionCategory.Escrow){
      rs.push(
        <div className="transaction-details">
          <span>{ getTime() }</span>
          <span className="separator">|</span>
          <span>{ deliveryStatus }</span>
          <span className="separator">|</span>
          <span>{ settlementStatus }</span>
          <span className="separator">|</span>
          <span>{ cancelStatus }</span>
          {
            (!!installmentMonth && parseInt(installmentMonth) > 1) && 
              <>
                <span className="separator">|</span>
                <span>{ installmentMonth }개월 할부</span>
              </>
          }
        </div>
      );
    }
    else if(transactionCategory === TransactionCategory.Billing){
      rs.push(
        <div className="transaction-details">
          <span>{ getTime() }</span>
          <span className="separator">|</span>
          <span>{ processResult }</span>
          <span className="separator">|</span>
          <span>{ paymentMethod }</span>
        </div>
      );
    }
    return rs;
  };

  return (
    <>
      <div 
        className={ `transaction-item ${getItemClass()}` }
        onClick={ () => onClickToNavigate() }
      >
        <div className="transaction-status">
          <div className={ `status-dot ${getDotClass()}`}></div>
        </div>
        <div className="transaction-content">
          <div className="transaction-title">{ getTitle() }</div>
          { getDetail() }
        </div>
        <div className="transaction-amount">
          <NumericFormat
            value={ goodsAmount } 
            thousandSeparator
            displayType="text"
            suffix={ '원' }
          ></NumericFormat> 
        </div>
      </div>
    </>
  );
};
