import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useTranslation } from 'react-i18next';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useLocation } from 'react-router';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { useExtensionFundAccountTransferDetailMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-transfer-detail-mutation';
import { ExtensionFundAccountTransferDetailParams, ExtensionFundAccountTransferDetailResponse, ExtensionFundAccountTransferRegistParams, ExtensionFundAccountTransferRequestParams, ExtensionFundAccountTransferRequestResponse, FundAccountStatus } from '@/entities/additional-service/model/fund-account/types';
import { getFundAccountStatusName } from '@/entities/additional-service/model/fund-account/constant';
import moment from 'moment';
import { snackBar } from '@/shared/lib';
import { useExtensionFundAccountTransferRequestMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-transfer-request-mutation';

export const FundAccountTransferDetailPage = () => {
  const { t, i18n } = useTranslation();
  const { navigate } = useNavigate();
  const location = useLocation();

  const seq = location.state.seq;

  const [detail, setDetail] = useState<ExtensionFundAccountTransferDetailResponse>();

  const { mutateAsync: extensionFundAccountTransferDetail } = useExtensionFundAccountTransferDetailMutation();
  const { mutateAsync: extensionFundAccountTransferRequest } = useExtensionFundAccountTransferRequestMutation();

  const callDetail = () => {
    let params: ExtensionFundAccountTransferDetailParams = {
      seq: seq
    };

    extensionFundAccountTransferDetail(params).then((rs: ExtensionFundAccountTransferDetailResponse) => {
      setDetail(rs);
    });
  };

  useSetHeaderTitle('자금이체 상세');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.fundAccount.transferList);
  });

  useEffect(() => {
    callDetail();
  }, []);

  const onClickToRequest = () => {
    let params: ExtensionFundAccountTransferRequestParams = {
      seq: seq
    };
    extensionFundAccountTransferRequest(params).then((rs: ExtensionFundAccountTransferRequestResponse) => {
      if (rs.status) {
        callDetail();
        snackBar("이체요청을 성공하였습니다.")
      } else {
        const errorMessage = rs.error?.message || '이체요청이 실패하였습니다.';
        snackBar(`[실패] ${errorMessage}`);
      }
    }).catch((error) => {
      const errorMessage = error?.response?.data?.error?.message ||
                          error?.message ||
                          '이체요청 중 오류가 발생했습니다.';
      snackBar(`[실패] ${errorMessage}`);
    });
  };

  return (
    <>
      <main className="full-height">
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="pay-top">
              <div className="num-amount">
                <span className="amount">
                  {t('home.money', { value: new Intl.NumberFormat('en-US').format(detail?.amount || 0) })}
                </span>
              </div>
              <div className="num-store">{detail?.accountName}({detail?.accountNo})</div>
              <div className="num-day">
                {detail?.registDate ? moment(detail.registDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD HH:mm:ss') : '-'}
              </div>
            </div>
            <div className="detail-divider"></div>
            <div className="pay-detail">
              <div className="detail-title">상세 정보</div>
              <ul className="kv-list">
                <li className="kv-row">
                  <span className="k">등록일시</span>
                  <span className="v">
                    {detail?.registDate ? moment(detail.registDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD HH:mm:ss') : '-'}
                  </span>
                </li>
                <li className="kv-row">
                  <span className="k">처리결과</span>
                  <span className="v">{getFundAccountStatusName(t)(detail?.resultStatus) || '-'}</span>
                </li>
                <li className="kv-row">
                  <span className="k">요청일자</span>
                  <span className="v">
                    {detail?.requestDate ? moment(detail.requestDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD') : '-'}
                  </span>
                </li>
                <li className="kv-row">
                  <span className="k">이체결과</span>
                  <span className="v">{detail?.resultMessage || '-'}</span>
                </li>
                <li className="kv-row">
                  <span className="k">수취인명</span>
                  <span className="v">{detail?.accountName}</span>
                </li>
                <li className="kv-row">
                  <span className="k">은행</span>
                  <span className="v">{detail?.bankCode || '-'} </span>
                </li>
                <li className="kv-row">
                  <span className="k">계좌번호</span>
                  <span className="v">{detail?.accountNo}</span>
                </li>
                <li className="kv-row">
                  <span className="k">MID</span>
                  <span className="v">{detail?.mid}</span>
                </li>

              </ul>
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={() => onClickToRequest()}
                disabled={detail?.resultStatus !== FundAccountStatus.REGIST_COMPLETE}
              >이체 요청</button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};