/**
 * 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 { PanelLeft } from "lucide-react";
import { useTranslation } from "@pi-dash/i18n";
import { LinkIcon, SearchIcon } from "@pi-dash/propel/icons";
// pi dash imports
import { setToast, TOAST_TYPE } from "@pi-dash/propel/toast";
import { copyTextToClipboard } from "@pi-dash/utils";
// components
import type { TPowerKCommandConfig } from "@/components/power-k/core/types";
// hooks
import { useAppTheme } from "@/hooks/store/use-app-theme";
import { usePowerK } from "@/hooks/store/use-power-k";

export const usePowerKMiscellaneousCommands = (): TPowerKCommandConfig[] => {
  // store hooks
  const { toggleSidebar } = useAppTheme();
  const { topNavInputRef, topNavSearchInputRef } = usePowerK();
  // translation
  const { t } = useTranslation();

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

  const focusTopNavSearch = useCallback(() => {
    // Focus PowerK input if available, otherwise focus regular search input
    if (topNavSearchInputRef?.current) {
      topNavSearchInputRef.current.focus();
    } else if (topNavInputRef?.current) {
      topNavInputRef.current.focus();
    }
  }, [topNavInputRef, topNavSearchInputRef]);

  return [
    {
      id: "toggle_app_sidebar",
      group: "miscellaneous",
      type: "action",
      i18n_title: "Toggle app sidebar",
      icon: PanelLeft,
      action: () => toggleSidebar(),
      modifierShortcut: "cmd+b",
      isEnabled: () => true,
      isVisible: () => true,
      closeOnSelect: true,
    },
    {
      id: "copy_current_page_url",
      group: "miscellaneous",
      type: "action",
      i18n_title: "Copy current page URL",
      icon: LinkIcon,
      action: copyCurrentPageUrlToClipboard,
      modifierShortcut: "cmd+shift+c",
      isEnabled: () => true,
      isVisible: () => true,
      closeOnSelect: true,
    },
    {
      id: "focus_top_nav_search",
      group: "miscellaneous",
      type: "action",
      i18n_title: "Focus search input",
      icon: SearchIcon,
      action: focusTopNavSearch,
      modifierShortcut: "cmd+f",
      isEnabled: () => true,
      isVisible: () => true,
      closeOnSelect: true,
    },
  ];
};
