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, 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';
import { ExtensionLinkPayWaitDeleteParams, ExtensionLinkPayWaitDetailParams, LinkPaymentProcessStatus } from '@/entities/additional-service/model/link-pay/types';
import { snackBar } from '@/shared/lib';

export const LinkPaymentWaitDetailPage = () => {
  const { navigate } = useNavigate();
  const location = useLocation();
  const { mid, requestId } = 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,
      requestId: requestId
    }

    linkPayWaitDetail(detailParam).then((rs: DetailResponse) => {
      setTitleInfo(rs.titleInfo)
      setPaymentInfo(rs.paymentInfo)
    })

  }

  const deletePayment = () => {
    let deleteParam: ExtensionLinkPayWaitDeleteParams = {
      mid: mid,
      requestId: requestId
    }
    linkPayWaitDelete(deleteParam)
      .then((rs) => {
        onClickToNavigate(PATHS.additionalService.linkPayment.pendingSend)
        snackBar("삭제를 성공하였습니다.")
      })
      .catch((error) => {
        console.error("Resend 실패: ", error);
        snackBar(`[실패] ${error?.response?.data?.message}`)
      });
  }

  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()}
              disabled={paymentInfo?.processStatus !== LinkPaymentProcessStatus.SEND_REQUEST}
            >삭제</button>
          </div>
        </div>
      </main >
    </>
  )
};