/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useCallback } from "react";
import { useParams } from "next/navigation";
import { Star, StarOff, Users } from "lucide-react";
// pi dash imports
import { EUserPermissionsLevel } from "@pi-dash/constants";
import { useTranslation } from "@pi-dash/i18n";
import { LinkIcon, ModuleStatusIcon } from "@pi-dash/propel/icons";
import { setToast, TOAST_TYPE } from "@pi-dash/propel/toast";
import type { IModule, TModuleStatus } from "@pi-dash/types";
import { EUserPermissions } from "@pi-dash/types";
import { copyTextToClipboard } from "@pi-dash/utils";
// components
import type { TPowerKCommandConfig } from "@/components/power-k/core/types";
// hooks
import { useModule } from "@/hooks/store/use-module";
import { useUser } from "@/hooks/store/user";

export const usePowerKModuleContextBasedActions = (): TPowerKCommandConfig[] => {
  // navigation
  const { workspaceSlug, projectId, moduleId } = useParams();
  // store
  const {
    permission: { allowPermissions },
  } = useUser();
  const { getModuleById, addModuleToFavorites, removeModuleFromFavorites, updateModuleDetails } = useModule();
  // derived values
  const moduleDetails = moduleId ? getModuleById(moduleId.toString()) : null;
  const isFavorite = !!moduleDetails?.is_favorite;
  // permission
  const isEditingAllowed =
    allowPermissions([EUserPermissions.ADMIN, EUserPermissions.MEMBER], EUserPermissionsLevel.PROJECT) &&
    !moduleDetails?.archived_at;
  // translation
  const { t } = useTranslation();

  const handleUpdateModule = useCallback(
    async (formData: Partial<IModule>) => {
      if (!workspaceSlug || !projectId || !moduleDetails) return;
      await updateModuleDetails(workspaceSlug.toString(), projectId.toString(), moduleDetails.id, formData).catch(
        () => {
          setToast({
            type: TOAST_TYPE.ERROR,
            title: "Error!",
            message: "Module could not be updated. Please try again.",
          });
        }
      );
    },
    [moduleDetails, projectId, updateModuleDetails, workspaceSlug]
  );

  const handleUpdateMember = useCallback(
    (memberId: string) => {
      if (!moduleDetails) return;

      const updatedMembers = moduleDetails.member_ids ?? [];
      if (updatedMembers.includes(memberId)) updatedMembers.splice(updatedMembers.indexOf(memberId), 1);
      else updatedMembers.push(memberId);

      handleUpdateModule({ member_ids: updatedMembers });
    },
    [handleUpdateModule, moduleDetails]
  );

  const toggleFavorite = useCallback(() => {
    if (!workspaceSlug || !moduleDetails || !moduleDetails.project_id) return;
    try {
      if (isFavorite) removeModuleFromFavorites(workspaceSlug.toString(), moduleDetails.project_id, moduleDetails.id);
      else addModuleToFavorites(workspaceSlug.toString(), moduleDetails.project_id, moduleDetails.id);
    } catch {
      setToast({
        type: TOAST_TYPE.ERROR,
        title: "Some error occurred",
      });
    }
  }, [addModuleToFavorites, removeModuleFromFavorites, workspaceSlug, moduleDetails, isFavorite]);

  const copyModuleUrlToClipboard = useCallback(() => {
    const url = new URL(window.location.href);
    copyTextToClipboard(url.href)
      .then(() => {
        setToast({
          type: TOAST_TYPE.SUCCESS,
          title: t("Module URL copied to clipboard."),
        });
      })
      .catch(() => {
        setToast({
          type: TOAST_TYPE.ERROR,
          title: t("Some error occurred while copying the module URL to clipboard."),
        });
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return [
    {
      id: "add_remove_module_members",
      i18n_title: "Add/remove members",
      icon: Users,
      group: "contextual",
      contextType: "module",
      type: "change-page",
      page: "update-module-member",
      onSelect: (data) => {
        const memberId = data as string;
        handleUpdateMember(memberId);
      },
      shortcut: "m",
      isEnabled: () => isEditingAllowed,
      isVisible: () => isEditingAllowed,
      closeOnSelect: false,
    },
    {
      id: "change_module_status",
      i18n_title: "Change status",
      iconNode: <ModuleStatusIcon status="backlog" className="size-3.5 shrink-0" />,
      group: "contextual",
      contextType: "module",
      type: "change-page",
      page: "update-module-status",
      onSelect: (data) => {
        const status = data as TModuleStatus;
        handleUpdateModule({ status });
      },
      shortcut: "s",
      isEnabled: () => isEditingAllowed,
      isVisible: () => isEditingAllowed,
      closeOnSelect: true,
    },
    {
      id: "toggle_module_favorite",
      i18n_title: isFavorite
        ? "Remove from favorites"
        : "Add to favorites",
      icon: isFavorite ? StarOff : Star,
      group: "contextual",
      contextType: "module",
      type: "action",
      action: toggleFavorite,
      modifierShortcut: "shift+f",
      isEnabled: () => isEditingAllowed,
      isVisible: () => isEditingAllowed,
      closeOnSelect: true,
    },
    {
      id: "copy_module_url",
      i18n_title: "Copy URL",
      icon: LinkIcon,
      group: "contextual",
      contextType: "module",
      type: "action",
      action: copyModuleUrlToClipboard,
      modifierShortcut: "cmd+shift+,",
      isEnabled: () => true,
      isVisible: () => true,
      closeOnSelect: true,
    },
  ];
};
