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, ExtensionLinkPayHistoryDetailParams, ExtensionLinkPayHistoryResendParams, 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';

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

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

  const [titleInfo, setTitleInfo] = useState<TitleInfo>();
  const [detailInfo, setDetailInfo] = useState<DetailInfo>();
  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>();

  const [showPayment, setShowPayment] = useState<boolean>(false);

  useSetHeaderTitle('링크결제 상세');
  useSetHeaderType(HeaderType.RightClose);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.linkPayment.shippingHistory);
  });
  useSetFooterMode(false);

  const { mutateAsync: linkPayHistoryDetail } = useExtensionLinkPayHistoryDetailMutation();
  const { mutateAsync: linkPayHistoryResend } = useExtensionLinkPayHistoryResendMutation();
  const callDetail = () => {
    let detailParam: ExtensionLinkPayHistoryDetailParams = {
      mid: mid,
      tid: tid
    }
    linkPayHistoryDetail(detailParam).then((rs: DetailResponse) => {
      console.log("Detail Info: ", rs)
      setTitleInfo(rs.titleInfo)
      setDetailInfo(rs.detailInfo)
      setPaymentInfo(rs.paymentInfo)
    })
  }

  const resendPayment = () => {
    let resendParam: ExtensionLinkPayHistoryResendParams = {
      mid: mid,
      tid: tid
    }
    linkPayHistoryResend(resendParam)
      .then((response) => {
        console.log("Resend 성공 응답: ", response);
        onClickToNavigate(PATHS.additionalService.linkPayment.shippingHistory)
      })
      .catch((error) => {
        console.error("Resend 실패: ", error);

      });
  }

  const onClickToNavigate = (path: string) => {
    navigate(path)
  };

  const onClickToShowInfo = () => {
    setShowPayment(!showPayment);
  };

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

    overlay.open(({
      isOpen,
      close,
      unmount
    }) => {
      return (
        <Dialog
          afterLeave={unmount}
          open={isOpen}
          onClose={close}
          onConfirmClick={() => resendPayment()}
          message={msg}
          buttonLabel={['취소', '확인']}
        />
      );
    });
  };
  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>
          </div>
          <div className="apply-row">
            <button
              className="btn-50 btn-blue flex-1"
              onClick={() => onClickToCancel()}
            >재발송</button>
          </div>
        </div>
      </main >
    </>
  )
};