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 { TitleInfoWrap } from '@/entities/additional-service/ui/info-wrap/title-info-wrap';
import { AdditionalServiceCategory, DetailResponse, ExtensionLinkPayWaitDeleteParams, ExtensionLinkPayWaitDetailParams, PaymentInfo, TitleInfo } from '@/entities/additional-service/model/types';
import { useExtensionLinkPayWaitDetailMutation, } from '@/entities/additional-service/api/link-payment/use-extension-link-pay-wait-detail-mutation';
import { PaymentInfoWrap } from '@/entities/additional-service/ui/info-wrap/payment-info-wrap';
import { useExtensionLinkPayWaitDeleteMutation } from '@/entities/additional-service/api/link-payment/use-extension-link-pay-wait-delete-mutation';

export const LinkPaymentWaitDetailPage = () => {
  const { navigate } = useNavigate();
  const location = useLocation();
  const { mid, tid } = location.state || {};
  const [titleInfo, setTitleInfo] = useState<TitleInfo>();
  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>();

  useSetHeaderTitle('링크결제 상세_발송대기');
  useSetHeaderType(HeaderType.RightClose);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.linkPayment.pendingSend);
  });
  useSetFooterMode(false);

  const { mutateAsync: linkPayWaitDetail } = useExtensionLinkPayWaitDetailMutation();
  const { mutateAsync: linkPayWaitDelete } = useExtensionLinkPayWaitDeleteMutation();
  const callDetail = () => {
    let detailParam: ExtensionLinkPayWaitDetailParams = {
      mid: mid,
      tid: tid
    }

    linkPayWaitDetail(detailParam).then((rs: DetailResponse) => {
      console.log("Detail Info: ", rs)
      setTitleInfo(rs.titleInfo)
      setPaymentInfo(rs.paymentInfo)
    })

  }

  const deletePayment = () => {
    let deleteParam: ExtensionLinkPayWaitDeleteParams = {
      mid: mid,
      tid: tid
    }
    linkPayWaitDelete(deleteParam)
      .then((response) => {
        console.log("Delete 성공 응답: ", response)
        onClickToNavigate(PATHS.additionalService.linkPayment.pendingSend)
      })
      .catch((error) => {
        console.error("Resend 실패: ", error);

      });
  }

  const onClickToNavigate = (path: string) => {
    let timeout = setTimeout(() => {
      clearTimeout(timeout);
      navigate(PATHS.additionalService.linkPayment.pendingSend, {
      });
    }, 10)
  };

  const onClickToCancel = () => {
    let msg = '삭제 하시겠습니까?';

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

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="pay-top">
              <TitleInfoWrap
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentWait}
                titleInfo={titleInfo}
              ></TitleInfoWrap>
            </div>
            <div className="pay-detail">
              <div className="detail-divider"></div>
              <PaymentInfoWrap
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentWait}
                paymentInfo={paymentInfo}
              ></PaymentInfoWrap>
            </div>
          </div>
          <div className="apply-row">
            <button
              className="btn-50 btn-blue flex-1"
              onClick={() => onClickToCancel()}
            >삭제</button>
          </div>
        </div>
      </main >
    </>
  )
};