

import { observer } from "mobx-react";
import { useState } from "react";
// ui
import { TOAST_TYPE, setToast } from "@buzzwaretech/propel/toast";
import { AlertModalCore } from "@buzzwaretech/ui";
import { getPageName } from "@buzzwaretech/utils";
import { useParams } from "next/navigation";
// constants
// buzzwareTech web hooks
import { useAppRouter } from "@/hooks/use-app-router";
import type { EPageStoreType } from "@/buzzwareTech-web/hooks/store";
import { usePageStore } from "@/buzzwareTech-web/hooks/store";
// store
import type { TPageInstance } from "@/store/pages/base-page";

type TConfirmPageDeletionProps = {
  isOpen: boolean;
  onClose: () => void;
  page: TPageInstance;
  storeType: EPageStoreType;
};

export const DeletePageModal = observer(function DeletePageModal(
  props: TConfirmPageDeletionProps,
) {
  const { isOpen, onClose, page, storeType } = props;
  // states
  const [isDeleting, setIsDeleting] = useState(false);
  // store hooks
  const { removePage } = usePageStore(storeType);

  // derived values
  const { id: pageId, name } = page;

  const handleClose = () => {
    setIsDeleting(false);
    onClose();
  };

  const router = useAppRouter();
  const { pageId: routePageId } = useParams();

  const handleDelete = async () => {
    if (!pageId) return;
    setIsDeleting(true);
    await removePage({ pageId })
      .then(() => {
        handleClose();
        setToast({
          type: TOAST_TYPE.SUCCESS,
          title: "Success!",
          message: "Page deleted successfully.",
        });

        if (routePageId) {
          router.back();
        }
      })
      .catch(() => {
        setToast({
          type: TOAST_TYPE.ERROR,
          title: "Error!",
          message: "Page could not be deleted. Please try again.",
        });
      });

    setIsDeleting(false);
  };

  if (!page || !page.id) return null;

  return (
    <AlertModalCore
      handleClose={handleClose}
      handleSubmit={handleDelete}
      isSubmitting={isDeleting}
      isOpen={isOpen}
      title="Delete page"
      content={
        <>
          Are you sure you want to delete page-{" "}
          <span className="font-medium break-words break-all text-primary">
            {getPageName(name)}
          </span>{" "}
          ? The Page will be deleted permanently. This action cannot be undone.
        </>
      }
    />
  );
});
