"use client";

import {
  Button,
  Dialog,
  DialogBody,
  DialogFooter,
  Typography,
} from "@material-tailwind/react";
import React, { useCallback, useState } from "react";
import { IoRefresh } from "react-icons/io5";

import { _useScopedI18n } from "../../i18n/client";
import ButtonCustom from "../Button";
import LoadingIconComponent from "../LoadingIconComponent";

/** Same props as {@link RequestProcessingDialog} plus optional cancel confirmation before close. */
export type RequestProcessingWithCancelConfirmProps = {
  open: boolean;
  orderId: string;
  paymentProcessFailed: boolean;
  onRetry?: () => void;
  setOpen: (value: boolean) => void;
  paymentDetails?: React.ReactNode;
  /** When true (with `onConfirmLeavePayment`), Cancel opens a confirmation dialog first. */
  confirmBeforeClose?: boolean;
  /** Called when the user confirms leaving the payment flow (e.g. navigate home). */
  onConfirmLeavePayment?: () => void;
  /** Optional copy variant for cancel confirmation dialog. Defaults to nowpayments wording. */
  cancelConfirmVariant?: "nowpayments" | "stripe";
};

/**
 * Copy of the payment {@link RequestProcessingDialog} with an optional second dialog to confirm
 * before closing during an active payment (e.g. NOWPayments deposit instructions).
 */
export function RequestProcessingWithCancelConfirm({
  open,
  setOpen,
  orderId,
  paymentProcessFailed,
  onRetry,
  paymentDetails,
  confirmBeforeClose,
  onConfirmLeavePayment,
  cancelConfirmVariant = "nowpayments",
}: RequestProcessingWithCancelConfirmProps) {
  const scopeT = _useScopedI18n("payment.requestProcessingDialog");
  const cancelT = _useScopedI18n("payment.cancelPaymentConfirm");
  const stripeCancelT = _useScopedI18n("payment.cancelPaymentConfirmStripe");
  const hasPaymentDetails = Boolean(paymentDetails);
  const [cancelConfirmOpen, setCancelConfirmOpen] = useState(false);

  const useConfirmFlow = Boolean(
    confirmBeforeClose && onConfirmLeavePayment,
  );

  const handleCloseClick = useCallback(() => {
    if (useConfirmFlow) {
      setCancelConfirmOpen(true);
      return;
    }
    setOpen(false);
  }, [useConfirmFlow, setOpen]);

  const handleConfirmLeave = useCallback(() => {
    setCancelConfirmOpen(false);
    setOpen(false);
    onConfirmLeavePayment?.();
  }, [onConfirmLeavePayment, setOpen]);

  const handleStayOnPayment = useCallback(() => {
    setCancelConfirmOpen(false);
  }, []);

  const isStripeVariant = cancelConfirmVariant === "stripe";

  return (
    <>
      <Dialog
        open={open}
        size={hasPaymentDetails ? "md" : "xs"}
        handler={() => {}}
        className={`p-2 md:p-4 ${hasPaymentDetails ? "max-w-md w-[calc(100vw-1.5rem)]" : ""}`}
      >
        <DialogBody
          className={
            hasPaymentDetails
              ? "flex max-h-[80vh] flex-col gap-3 overflow-y-auto px-1 text-left sm:px-2"
              : "flex flex-col items-center gap-8 text-center"
          }
        >
          {hasPaymentDetails ? (
            <>
              <div className="w-full space-y-1 text-center">
                <Typography
                  variant="h3"
                  className="text-xl font-semibold text-slate-900"
                >
                  {scopeT("completePaymentTitle")}
                </Typography>
                <p className="text-sm text-slate-500">
                  {scopeT("orderId")}{" "}
                  <span className="font-mono font-medium text-slate-700">
                    {orderId}
                  </span>
                </p>
              </div>

              {paymentDetails}

              {paymentProcessFailed ? (
                <div className="text-center">
                  <Typography
                    variant="lead"
                    className="mb-3 text-sm font-medium text-slate-500"
                  >
                    {scopeT("errorMsg")}
                  </Typography>

                  <ButtonCustom
                    icon={<IoRefresh className="size-4" />}
                    onClick={onRetry}
                  >
                    {scopeT("retryBtn")}
                  </ButtonCustom>
                </div>
              ) : null}
            </>
          ) : (
            <>
              <LoadingIconComponent />
              <div>
                <Typography variant="h3" className="text-xl text-black-500">
                  {scopeT("title")}...
                </Typography>
              </div>

              <div className="rounded-lg border border-slate-100 bg-gray-50 px-9 py-4">
                <Typography
                  variant="h6"
                  className="text-xs font-medium leading-5 text-black-500"
                >
                  {scopeT("orderId")} : {orderId}
                </Typography>
              </div>

              <div>
                {paymentProcessFailed ? (
                  <>
                    <Typography
                      variant="lead"
                      className="mb-3 text-sm font-medium text-slate-500"
                    >
                      {scopeT("errorMsg")}
                    </Typography>

                    <ButtonCustom
                      icon={<IoRefresh className="size-4" />}
                      onClick={onRetry}
                    >
                      {scopeT("retryBtn")}
                    </ButtonCustom>
                  </>
                ) : (
                  <>
                    <Typography
                      variant="lead"
                      className="mb-3 text-sm font-medium text-slate-500"
                    >
                      {scopeT("subTitle")}
                    </Typography>

                    <Typography
                      variant="lead"
                      className="text-sm font-medium text-slate-500"
                    >
                      {scopeT("message")}
                    </Typography>
                  </>
                )}
              </div>
            </>
          )}
        </DialogBody>
        <DialogFooter className="flex justify-end border-0 p-0 pt-3 shadow-none sm:px-2">
          <Button
            variant="outlined"
            color="blue-gray"
            className="normal-case rounded-xl border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm hover:border-slate-400 hover:bg-slate-50"
            onClick={handleCloseClick}
          >
            {cancelT("cancelBtn")}
          </Button>
        </DialogFooter>
      </Dialog>

      <Dialog
        open={cancelConfirmOpen}
        size="xs"
        handler={handleStayOnPayment}
        className="p-2 md:p-5 z-[10001]"
      >
        <DialogBody className="space-y-3 px-1 py-2">
          <Typography
            variant="h4"
            className="text-base md:text-xl font-semibold text-black-500"
          >
            {isStripeVariant ? stripeCancelT("title") : cancelT("title")}
          </Typography>
          <ul className="list-disc space-y-3 pl-5 text-sm leading-relaxed text-slate-600 marker:text-slate-500">
            {isStripeVariant ? (
              <>
                <li>{stripeCancelT("item1")}</li>
                <li>{stripeCancelT("item2")}</li>
                <li>{stripeCancelT("item3")}</li>
              </>
            ) : (
              <>
                <li>{cancelT("completedItem")}</li>
                <li>
                  <span className="block">{cancelT("notSentIntro")}</span>
                  <ul className="mt-2 list-[circle] space-y-2 pl-5 marker:text-slate-400">
                    <li>{cancelT("notSentSub1")}</li>
                    <li>{cancelT("notSentSub2")}</li>
                    <li>{cancelT("notSentSub3")}</li>
                  </ul>
                </li>
              </>
            )}
          </ul>
          <Typography className="text-sm leading-relaxed text-slate-600">
            {isStripeVariant ? stripeCancelT("closing") : cancelT("closing")}
          </Typography>
        </DialogBody>
        <DialogFooter className="flex flex-col-reverse gap-2 p-0 pt-2 sm:flex-row sm:justify-end">
          <Button
            variant="outlined"
            color="blue-gray"
            className="normal-case rounded-xl border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm hover:border-slate-400 hover:bg-slate-50"
            onClick={handleStayOnPayment}
          >
            {isStripeVariant ? stripeCancelT("stayBtn") : cancelT("stayBtn")}
          </Button>
          <ButtonCustom icon={undefined} onClick={handleConfirmLeave}>
            {isStripeVariant ? stripeCancelT("leaveBtn") : cancelT("leaveBtn")}
          </ButtonCustom>
        </DialogFooter>
      </Dialog>
    </>
  );
}
