

import { observer } from "mobx-react";
import { useParams } from "next/navigation";
import { useState } from "react";
// types
import { PROJECT_ERROR_MESSAGES } from "@buzzwaretech/constants";
import { useTranslation } from "@buzzwaretech/i18n";
import { TOAST_TYPE, setToast } from "@buzzwaretech/propel/toast";
import type { IModule } from "@buzzwaretech/types";
// ui
import { AlertModalCore } from "@buzzwaretech/ui";
// constants
// hooks
import { useModule } from "@/hooks/store/use-module";
import { useAppRouter } from "@/hooks/use-app-router";

type Props = {
  data: IModule;
  isOpen: boolean;
  onClose: () => void;
};

export const DeleteModuleModal = observer(function DeleteModuleModal(
  props: Props,
) {
  const { data, isOpen, onClose } = props;
  // states
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  // router
  const router = useAppRouter();
  const { workspaceSlug, projectId, moduleId, peekModule } = useParams();
  // store hooks
  const { deleteModule } = useModule();
  const { t } = useTranslation();

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

  const handleDeletion = async () => {
    if (!workspaceSlug || !projectId) return;

    setIsDeleteLoading(true);

    await deleteModule(workspaceSlug.toString(), projectId.toString(), data.id)
      .then(() => {
        if (moduleId || peekModule)
          router.push(`/${workspaceSlug}/projects/${data.project_id}/modules`);
        handleClose();
        setToast({
          type: TOAST_TYPE.SUCCESS,
          title: "Success!",
          message: "Module deleted successfully.",
        });
      })
      .catch((errors) => {
        const isPermissionError =
          errors?.error === "You don't have the required permissions.";
        const currentError = isPermissionError
          ? PROJECT_ERROR_MESSAGES.permissionError
          : PROJECT_ERROR_MESSAGES.moduleDeleteError;
        setToast({
          title: t(currentError.i18n_title),
          type: TOAST_TYPE.ERROR,
          message: currentError.i18n_message && t(currentError.i18n_message),
        });
      })
      .finally(() => handleClose());
  };

  return (
    <AlertModalCore
      handleClose={handleClose}
      handleSubmit={handleDeletion}
      isSubmitting={isDeleteLoading}
      isOpen={isOpen}
      title="Delete module"
      content={
        <>
          Are you sure you want to delete module-{" "}
          <span className="font-medium break-all text-primary">
            {data?.name}
          </span>
          ? All of the data related to the module will be permanently removed.
          This action cannot be undone.
        </>
      }
    />
  );
});
