import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
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';
import { useTranslation } from 'react-i18next';
import { DetailMotionDuration, DetailMotionStyle, DetailMotionVariants } from '@/entities/common/model/constant';
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';

export interface LinkPaymentWaitDetailProps {
  detailOn: boolean;
  setDetailOn: (detailOn: boolean) => void;
  mid: string;
  requestId: string;
};

export const LinkPaymentWaitDetail = ({
  detailOn,
  setDetailOn,
  mid,
  requestId
}: LinkPaymentWaitDetailProps) => {
  const { t } = useTranslation();
  const [titleInfo, setTitleInfo] = useState<TitleInfo>();
  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>();

  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) => {
        callDetail();
        snackBar(t('additionalService.linkPayment.deleteSuccess'))
      })
      .catch((error) => {
        snackBar(`[${t('common.failed')}] ${error?.response?.data?.message}`)
      });
  }

  const onClickToCancel = () => {
    let msg = t('additionalService.linkPayment.deleteConfirm');

    overlay.open(({
      isOpen,
      close,
      unmount
    }) => {
      return (
        <Dialog
          afterLeave={unmount}
          open={isOpen}
          onClose={close}
          onConfirmClick={() => deletePayment()}
          message={msg}
          buttonLabel={[t('common.cancel'), t('common.confirm')]}
        />
      );
    });
  };

  const onClickToClose = () => {
    setDetailOn(false);
  };

  useEffect(() => {
    if(!!mid && !!requestId){
      callDetail();
    }
  }, [mid, requestId]);

  return (
    <>
      <motion.div 
        className="full-menu-modal" 
        initial="hidden"
        animate={ (detailOn)? 'visible': 'hidden' }
        variants={ DetailMotionVariants }
        transition={ DetailMotionDuration }
        style={ DetailMotionStyle }
      >
        <div className="full-menu-container pdw-16">
          <div className="full-menu-header">
            <div className="full-menu-title center">{ t('additionalService.linkPayment.waitDetailTitle') }</div>
            <div className="full-menu-actions">
              <FullMenuClose
                addClass="full-menu-close"
                onClickToCallback={ onClickToClose }
              ></FullMenuClose>
            </div>
          </div>
          <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}
            >{t('additionalService.linkPayment.delete')}</button>
          </div>
        </div>
      </motion.div>
    </>
  )
};