import { useEffect, useState } from 'react';
import { PATHS } from '@/shared/constants/paths';
import { useLocation } from 'react-router';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetOnBack,
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { overlay } from 'overlay-kit';
import { Dialog } from '@/shared/ui/dialogs/dialog';
import { useExtensionLinkPayHistoryDetailMutation } from '@/entities/additional-service/api/link-payment/use-extension-link-pay-history-detail-mutation';
import { AdditionalServiceCategory, DetailInfo, DetailResponse, PaymentInfo, TitleInfo } from '@/entities/additional-service/model/types';
import { TitleInfoWrap } from '@/entities/additional-service/ui/info-wrap/title-info-wrap';
import { PaymentInfoWrap } from '@/entities/additional-service/ui/info-wrap/payment-info-wrap';
import { DetailInfoWrap } from '@/entities/additional-service/ui/info-wrap/detail-info-wrap';
import { useExtensionLinkPayHistoryResendMutation } from '@/entities/additional-service/api/link-payment/use-extension-link-pay-history-resend-mutation';
import { ExtensionLinkPayHistoryDetailParams, ExtensionLinkPayHistoryResendParams } from '@/entities/additional-service/model/link-pay/types';
import { snackBar } from '@/shared/lib';
import moment from 'moment';

export const LinkPaymentDetailPage = () => {
  const { navigate } = useNavigate();
  const location = useLocation();

  const { mid, tid, requestId, subReqId } = location.state || {};

  const [titleInfo, setTitleInfo] = useState<TitleInfo>();
  const [detailInfo, setDetailInfo] = useState<DetailInfo>();
  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>();
  const [detailExposure, setDetailExposure] = useState<boolean>(false);
  const [showPayment, setShowPayment] = useState<boolean>(false);

  useSetHeaderTitle('링크결제 상세');
  useSetHeaderType(HeaderType.RightClose);
  useSetOnBack(() => {
    navigate(-1); // 브라우저 히스토리를 이용한 뒤로가기
  });
  useSetFooterMode(false);

  const { mutateAsync: linkPayHistoryDetail } = useExtensionLinkPayHistoryDetailMutation();
  const { mutateAsync: linkPayHistoryResend } = useExtensionLinkPayHistoryResendMutation();
  
  // 상세내역 조회
  const callDetail = () => {
    let detailParam: ExtensionLinkPayHistoryDetailParams = {
      mid: mid,
      requestId: requestId,
      subReqId: subReqId
    }
    linkPayHistoryDetail(detailParam).then((rs: DetailResponse) => {
      console.log("Detail Info: ", rs)
      setTitleInfo(rs.titleInfo)
      setDetailInfo(rs.detailInfo)
      setPaymentInfo(rs.paymentInfo)
      setDetailExposure(rs.detailExposure ?? false)
    })
  }

  //재발송 API
  const resendPayment = () => {
    let resendParam: ExtensionLinkPayHistoryResendParams = {
      mid: mid,
      requestId: requestId,
      sendMethod: paymentInfo?.sendMethod
    }
    linkPayHistoryResend(resendParam)
      .then((response) => {
        if (response.status) {
          snackBar("재발송을 성공하였습니다.");
          callDetail();
        } else {
          const errorMessage = response.error?.message || '재발송이 실패하였습니다.';
          snackBar(`[실패] ${errorMessage}`);
        }
      })
      .catch((error) => {
        const errorMessage = error?.response?.data?.error?.message ||
                            error?.message ||
                            '재발송 중 오류가 발생했습니다.';
        snackBar(`[실패] ${errorMessage}`);
      });
  }

  const onClickToResend = () => {
    let msg = '재발송 하시겠습니까?';

    overlay.open(({
      isOpen,
      close,
      unmount
    }) => {
      return (
        <Dialog
          afterLeave={unmount}
          open={isOpen}
          onClose={close}
          onConfirmClick={() => resendPayment()}
          message={msg}
          buttonLabel={['취소', '확인']}
        />
      );
    });
  };

  const onClickToSeparateApproval = () => {
    navigate(PATHS.additionalService.linkPayment.separateApproval, {
      state: { mid, requestId }
    });
  };

  // 재발송 버튼 활성화 조건 체크
  const isResendEnabled = () => {
    // paymentStatus가 "ACTIVE"이고
    if (paymentInfo?.paymentStatus !== 'ACTIVE') {
      return false;
    }

    // paymentLimitDate가 오늘 날짜를 지나지 않았을 때
    if (paymentInfo?.paymentLimitDate) {
      const limitDate = moment(paymentInfo.paymentLimitDate, 'YYYYMMDD');
      const today = moment().startOf('day');
      return limitDate.isSameOrAfter(today);
    }

    return false;
  };

  useEffect(() => {
    callDetail();
  }, []);
  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="pay-top">
              <TitleInfoWrap
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
                titleInfo={titleInfo}
              ></TitleInfoWrap>
            </div>
            <div className="pay-detail">
              <div className="detail-divider"></div>
              <PaymentInfoWrap
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
                paymentInfo={paymentInfo}
              ></PaymentInfoWrap>
              <div className="detail-divider"></div>
              <DetailInfoWrap
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
                detailInfo={detailInfo}
              ></DetailInfoWrap>
              <div className="link-payment-detail-button">
                <button
                  className="btn-50 btn-blue flex-1"
                  onClick={() => onClickToSeparateApproval()}
                  disabled={detailExposure}
                >분리승인 상세</button>
              </div>
            </div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={() => onClickToResend()}
                disabled={!isResendEnabled()}
              >재발송</button>
            </div>
          </div>
        </div>
      </main >
    </>
  )
};