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 { getAllTransactionStatusCode } from '../model/contant';
import { useTranslation } from 'react-i18next';

export const ListItem = ({
  transactionCategory,
  tid, mid, statusCode,
  installmentMonth, serviceName, serviceCode,
  serviceDetailName, goodsAmount,
  amount, customerName, issueNumber, approvalNumber,
  paymentMethod, processResult, transactionType,
  transactionDateTime, transactionAmount,
  deliveryStatus, settlementStatus,
  cancelStatus, billKey, orderNumber
}: ListItemProps) => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  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: {
          tid: tid
        }
      });
    }
    else if(transactionCategory === TransactionCategory.Escrow){
      navigate(PATHS.transaction.escrow.detail, {
        state: {
         tid: tid,
         serviceCode: serviceCode
        }
      });
    }
    else if(transactionCategory === TransactionCategory.Billing){
      navigate(PATHS.transaction.billing.detail, {
        state: {
          tid: tid,
        }
      });
    }
    else{
      alert(t('common.error'));
    }
  };
  
  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){
      const allTransactionStatusCode = getAllTransactionStatusCode(t);
      Loop1:
      for(let i=0;i<allTransactionStatusCode.length;i++){
        if(serviceCode === allTransactionStatusCode[i]?.serviceCode){
          let list = allTransactionStatusCode[i]?.list;
          if(!!list){
            Loop2:
            for(let j=0;j<list.length;j++){
              if(list[j]?.code === statusCode){
                str = list[j]?.name;
                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>{ t('transaction.fields.installmentMonthly', { count: parseInt(installmentMonth) }) }</span>
              </>
          }
        </div>
      );
    }
    else if(transactionCategory === TransactionCategory.CashReceipt){
      rs.push(
        <div className="transaction-details">
          <span>{ getTime() }</span>
          <span className="separator">|</span>
          <span>{ transactionType }</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>{ t('transaction.fields.installmentMonthly', { count: parseInt(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 || amount || transactionAmount }
            thousandSeparator
            displayType="text"
            suffix={ t('home.currencyWon') }
          ></NumericFormat>
        </div>
      </div>
    </>
  );
};
