import { NumericFormat } from 'react-number-format';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { ListItemProps, AdditionalServiceCategory } from '../model/types';
import { getPaymentStatusText, getProcessStatusText, getSendMethodText } from '../lib/payment-status-utils';
import { getFundAccountResultStatusName, getFundAccountStatusName } from '../model/fund-account/constant';
import moment from 'moment';
import { FundAccountResultStatus } from '../model/fund-account/types';
import { getSmsClName } from '../model/sms-payment/constant';
import { getKeyInPaymentPaymentStatusName } from '../model/key-in/constant';
import { getArsPaymentStatusName, getArsOrderStatusName } from '../model/ars/constant';
import { ServiceCode } from '../model/alimtalk/types';
import { getAlimtalkAlimClText, getAlimtalkSendClTypeText, getAlimtalkSendTypeText, getAlimtalkServiceCodeText } from '../model/alimtalk/constant';
import { getAuthResultStatusText, getTransTypeText } from '../model/face-auth/constant';
import { getPayoutStatusText } from '../model/payout/constant';

export const ListItem = ({
  additionalServiceCategory,
  mid, tid, orderDate, paymentStatus,
  orderTime,buyerPhoneLast4,statusColor,
  applicationDate, requestDate, bankName, accountNo, resultStatus, resultMessage,
  amount, sendMethod, processStatus, registDate,
  transactionTime,transactionCode,transactionType,
  accountName,submallId, settlementDate, companyName,orderStatus,

  alimCl, sendType, sendCl,
  paymentMethod, receiverName,
  requestId, subReqId,
  buyerName, receiverInfo,
  seq, serviceCode, sendDate,
  authStatus, status,

  smsCl, groupId, userMallId, transType,
  authResult, failReason, requestTime,
  resendEnabled,
  onResendClick
}: ListItemProps) => {
  const { navigate } = useNavigate();
  const { t, i18n } = useTranslation();
  const getItemClass = () => {
    let rs = '';
    if (paymentStatus === '') {
      rs = '';
    }
    else if (paymentStatus === "APPROVAL") {
      rs = 'approved';
    }
    else if (paymentStatus === "ALL_CANCEL") {
      rs = 'refund';
    }
    else if (paymentStatus === 'AFTER_CANCEL') {
      rs = 'refund';
    }
    return rs;
  };

  const getDotClass = (str?: string) => {
    let rs = '';
    if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      if (transactionType === '') {
        rs = '';
      }
      else if (transactionType === "APPROVAL") {
        rs = 'blue';
      }
      else if (transactionType === "FULL_CANCEL") {
        rs = 'gray';
      }
      else if (transactionType === 'PARTIAL_CANCEL') {
        rs = 'gray';
      }

    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      if (authStatus === "REQUEST" || authStatus === "SUCCESS") {
        rs = 'blue';
      } else if (authStatus === "FAIL") {
        rs = 'gray';
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      if (resultStatus === "SUCCESS") {
        rs = 'blue';
      }
      else if (resultStatus === "FAIL") {
        rs = 'gray';
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      if (sendCl === "SUCCESS" || sendCl === "REQUEST") {
        rs = 'blue';
      } else {
        rs = 'gray';
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      if (authResult === "SUCCESS") {
        rs = 'blue';
      }
      else if (authResult === "FAIL") {
        rs = 'gray';
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentHistory) {
      if (paymentStatus === "0" || paymentStatus === "1" || paymentStatus === "2") {
        rs = 'blue';
      }
      else if (paymentStatus === "3") {
        rs = 'gray';
      }
      else if (paymentStatus === '4') {
        rs = 'gray';
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentWait) {
      if (processStatus === "SEND_REQUEST") {
        rs = 'blue'
      } else {
        rs = 'gray'
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.SMSPayment) {
      if (smsCl === "VACCOUNT_REQ_DEPOSIT") {
        rs = 'blue'
      } else {
        rs = 'gray'
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer) {
      if (resultStatus === "REQUEST_SUCCESS" || resultStatus === "REGIST_COMPLETE" || resultStatus === "TRANSFER_REQUEST") {
        rs = 'blue';
      } else if (resultStatus === "REQUEST_FAIL") {
        rs = 'gray';
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountResult) {
      if (resultStatus === "REQUEST" || resultStatus === "SUCCESS") {
        rs = 'blue';
      } else if (resultStatus === "FAIL") {
        rs = 'gray';
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.Payout) {
      if (status === "SUCCESS" || status === "REQUEST") {
        rs = 'blue';
      } else if (status === "FAIL") {
        rs = 'gray';
      }
    } else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      if (paymentStatus === "PENDING" || paymentStatus === "SUCCESS") {
        rs = 'blue';
      } else {
        rs = 'gray';
      }
    }
    return rs;

  };

  const onClickToNavigate = () => {
    // 상세페이지 없음
    if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment ||
      additionalServiceCategory === AdditionalServiceCategory.SMSPayment ||
      additionalServiceCategory === AdditionalServiceCategory.FaceAuth
    ) {

      return;
    }
    //이하 상세페이지 존재
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      navigate(PATHS.additionalService.accountHolderAuth.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid
        }
      })
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      navigate(PATHS.additionalService.accountHolderSearch.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentHistory) {
      navigate(PATHS.additionalService.linkPayment.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid,
          requestId: requestId,
          subReqId: subReqId
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentWait) {
      navigate(PATHS.additionalService.linkPayment.pendingDetail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid,
          requestId: requestId
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer) {
      navigate(PATHS.additionalService.fundAccount.transferDetail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          seq: seq
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountResult) {
      navigate(PATHS.additionalService.fundAccount.resultDetail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.SettlementAgency) {

    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Payout) {
      navigate(PATHS.additionalService.payout.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      navigate(PATHS.additionalService.ars.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid
        }
      });
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      navigate(PATHS.additionalService.alimtalk.detail, {
        state: {
          additionalServiceCategory: additionalServiceCategory,
          mid: mid,
          tid: tid,
        }
      });
    }
    // else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
    //   navigate(PATHS.additionalService.faceAuth.detail, {
    //     state: {
    //       additionalServiceCategory: additionalServiceCategory,
    //       mid: mid
    //     }
    //   })
    // }
    else {
      alert('additionalServiceCategory가 존재하지 않습니다.');
    }
  };

  const getTime = () => {
    let timeStr = '';
    if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      let time = transactionTime?.substring(0, 4);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      let time = requestDate?.substring(8, 14);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4) + ':' + time?.substring(4, 6);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      let time = requestDate?.substring(8, 14);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4) + ':' + time?.substring(4, 6);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      let time = requestDate?.substring(8, 14);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4) + ':' + time?.substring(4, 6);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer) {
      if (registDate && registDate.length >= 12) {
        timeStr = registDate.substring(8, 10) + ':' + registDate.substring(10, 12);
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountResult) {
      if (applicationDate && applicationDate.length >= 12) {
        timeStr = applicationDate.substring(8, 10) + ':' + applicationDate.substring(10, 12);
      } else {
        timeStr = requestDate?.substring(8, 10) + ':' + requestDate?.substring(10, 12);
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      timeStr = orderTime?.substring(0, 2) + ':' + orderTime?.substring(2, 4);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      let time = sendDate?.substring(8, 12);
      timeStr = time?.substring(0, 2) + ':' + time?.substring(2, 4);
    }
    else {
      return
    }
    return timeStr;
  };

  const getStatus = () => {
    let statusText = '';
    if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer) {
      statusText = getFundAccountStatusName(t)(resultStatus);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountResult) {
      statusText = getFundAccountResultStatusName(t)(resultStatus);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      statusText = resultStatus || '';
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      statusText = authStatus || '';
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      statusText = getTransTypeText(t)(transType)
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.SMSPayment) {
      statusText = getSmsClName(t)(smsCl);
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      statusText = getKeyInPaymentPaymentStatusName(t)(transactionType)
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      statusText = getArsPaymentStatusName(t)(paymentStatus)
    }
    else {
      statusText = resultStatus || status || '';
    }
    return statusText;
  };

  const getTitle = () => {
    let str: string | undefined = '';
    if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      str = `${transactionCode}`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      str = `${accountName}(${accountNo})`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      str = `${accountNo}`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      str = `${userMallId}(${mid})`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentHistory 
    ) {
      str = `${buyerName}`;
    } else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentWait) {
      str = `${buyerName}(${receiverInfo})`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Payout) {
      str = companyName;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer ||
      additionalServiceCategory === AdditionalServiceCategory.FundAccountResult
    ) {
      str = `${accountName}(${accountNo})`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.SMSPayment) {
      if (buyerPhoneLast4) {
        str = `${buyerName}(${buyerPhoneLast4})`
      } else {
        str = `${buyerName}`
      }
      
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      str = `${buyerName}(${tid})`;
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      str = `${receiverName}(${getAlimtalkSendTypeText(t)(sendType)})`;
    }

    return str;
  };

  const getDetail = () => {
    let rs = [];
    if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      rs.push(
        <div key='key-in-list' className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{getStatus()}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      rs.push(
        <div key="account-auth-list" className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{bankName}</span>
        </div>
      )
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      rs.push(
        <div key="account-search" className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{bankName}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      rs.push(
        <div key="face-auth" className="transaction-details">
          <span>{getStatus()}</span>
          <span className="separator">|</span>
          <span>
            {authResult === 'FAIL'
              ? `${getAuthResultStatusText(t)(authResult)}: ${failReason}`
              : getAuthResultStatusText(t)(authResult)
            }
          </span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentHistory) {
      if (paymentStatus === "0" || paymentStatus === "3" || paymentStatus === "4") {
        rs.push(
          <div key="link-payment-history" className="transaction-details">
            <span>{getPaymentStatusText(t)(paymentStatus)}</span>
            <span className="separator">|</span>
            <span>{getSendMethodText(t)(sendMethod)}</span>
          </div>
        )
      } else {
        rs.push(
          <div key="link-payment-history" className="transaction-details">
            <span>{getPaymentStatusText(t)(paymentStatus)}</span>
            <span className="separator">|</span>
            <span>{getSendMethodText(t)(sendMethod)}</span>
            <span className="separator">|</span>
            <span>{paymentMethod}</span>
          </div>
        );
      }
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentWait) {
      rs.push(
        <div key="link-payment-wait" className="transaction-details">
          <span>{getProcessStatusText(t)(processStatus)}</span>
          <span className="separator">|</span>
          <span>{getSendMethodText(t)(sendMethod)}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Payout) {
      rs.push(
        <div className="transaction-details">
          <span>{getPayoutStatusText(t)(status)}</span>
          <span className="separator">|</span>
          <span>{submallId}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer) {
      rs.push(
        <div key="fund-account-transfer" className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{getStatus()}</span>
          {resultMessage && (
            <>
              <span className="separator">|</span>
              <span>{resultMessage}</span>
            </>
          )}

        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountResult) {
      rs.push(
        <div key="fund-account-transfer" className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{getStatus()}</span>
          <span className="separator">|</span>
          <span>{mid}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      rs.push(
        <div className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{getStatus()}</span>
          <span className="separator">|</span>
          <span>{getArsOrderStatusName(t)(orderStatus)}</span>
          <span className="separator">|</span>
          <span>{transactionType}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      console.log(serviceCode)
      rs.push(
        <div className="transaction-details">
          <span>{getTime()}</span>
          <span className="separator">|</span>
          <span>{getAlimtalkServiceCodeText(t)(serviceCode)}</span>
          <span className="separator">|</span>
          <span>{getAlimtalkAlimClText(t)(alimCl)}</span>
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.SMSPayment) {
      rs.push(
        <div key="sms-payment" className="transaction-details">
          <span>{mid}</span>
          <span className="separator">|</span>
          <span>{getStatus()}</span>
        </div>
      )
    }
    return rs;
  };

  const getAmount = () => {
    let rs: any[] = [];
    if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderSearch) {
      rs.push(
        <div className={`status-label ${resultStatus === 'SUCCESS' ? 'success' : 'fail'}`}>
          {resultStatus === 'SUCCESS' ? t('additionalService.common.success') : t('additionalService.common.fail')}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FaceAuth) {
      rs.push(
        <div className={`status-label ${authResult === 'SUCCESS' ? 'success' : 'fail'}`}>
          {authResult === 'SUCCESS' ? t('additionalService.common.success') : t('additionalService.common.fail')}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.AccountHolderAuth) {
      const statusText = authStatus === 'REQUEST' ? t('additionalService.common.request') : authStatus === 'SUCCESS' ? t('additionalService.common.success') : t('additionalService.common.fail');
      const statusClass = authStatus === 'SUCCESS' || 'REQUEST' ? 'success' : 'fail';
      rs.push(
        <div className={`status-label ${statusClass}`}>
          {statusText}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.KeyInPayment) {
      rs.push(
        <div className="transaction-amount">
          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amount || 0) })}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.LinkPaymentHistory ||
      additionalServiceCategory === AdditionalServiceCategory.LinkPaymentWait
    ) {
      rs.push(
        <div className="transaction-amount">
          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amount || 0) })}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Payout) {
      rs.push(
        <div
          key="payout-item-amount"
          className="transaction-amount"
        >
          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amount || 0) })}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.FundAccountTransfer ||
      additionalServiceCategory === AdditionalServiceCategory.FundAccountResult
    ) {
      rs.push(
        <div
          key="fund-account-transfer-amount"
          className="transaction-amount"
        >
          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amount || 0) })}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Ars) {
      rs.push(
        <div
          key="payout-item-amount"
          className="transaction-amount"
        >
          {t('home.money', { value: new Intl.NumberFormat('en-US').format(amount || 0) })}
        </div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.Alimtalk) {
      rs.push(
        <div key="payout-item-amount" className={`status-label ${(sendCl === 'REQUEST' || sendCl === 'SUCCESS') ? 'success' : 'fail'}`}
        >{getAlimtalkSendClTypeText(t)(sendCl)}</div>
      );
    }
    else if (additionalServiceCategory === AdditionalServiceCategory.SMSPayment && onResendClick) {
      rs.push(
        <div
          key="sms-payment-amount"
          className={`status-label success`}
          onClick={() => mid && onResendClick(mid, tid || '')}
        >{t('additionalService.common.resend')}</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>
        {getAmount()}
      </div>
    </>
  );
};