/**
 * 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, useMemo } from "react";
import { observer } from "mobx-react";

import { useTranslation } from "@pi-dash/i18n";
import { LinkIcon, NewTabIcon, EditIcon, TrashIcon } from "@pi-dash/propel/icons";
import { TOAST_TYPE, setToast } from "@pi-dash/propel/toast";
import type { TContextMenuItem } from "@pi-dash/ui";
import { LinkItemBlock } from "@pi-dash/ui";
// pi dash utils
import { copyTextToClipboard } from "@pi-dash/utils";
// hooks
import { useHome } from "@/hooks/store/use-home";
// types
import type { TLinkOperations } from "./use-links";

export type TProjectLinkDetail = {
  linkId: string;
  linkOperations: TLinkOperations;
};

export const ProjectLinkDetail = observer(function ProjectLinkDetail(props: TProjectLinkDetail) {
  // props
  const { linkId, linkOperations } = props;
  // hooks
  const {
    quickLinks: { getLinkById, toggleLinkModal, setLinkData },
  } = useHome();
  const { t } = useTranslation();
  // derived values
  const linkDetail = getLinkById(linkId);
  const linkUrl = linkDetail?.url;

  // handlers
  const handleEdit = useCallback(
    (modalToggle: boolean) => {
      toggleLinkModal(modalToggle);
      setLinkData(linkDetail);
    },
    [linkDetail, setLinkData, toggleLinkModal]
  );

  const handleCopyText = useCallback(() => {
    if (!linkUrl) return;
    copyTextToClipboard(linkUrl).then(() => {
      setToast({
        type: TOAST_TYPE.SUCCESS,
        title: t("Link copied"),
        message: t("View link copied to clipboard."),
      });
    });
  }, [linkUrl, t]);

  const handleOpenInNewTab = useCallback(() => {
    window.open(linkUrl, "_blank", "noopener,noreferrer");
  }, [linkUrl]);

  const handleDelete = useCallback(() => {
    linkOperations.remove(linkId);
  }, [linkId, linkOperations]);

  // derived values
  const menuItems = useMemo<TContextMenuItem[]>(
    () => [
      {
        key: "edit",
        action: () => handleEdit(true),
        title: t("Edit"),
        icon: EditIcon,
      },
      {
        key: "open-new-tab",
        action: handleOpenInNewTab,
        title: t("Open in new tab"),
        icon: NewTabIcon,
      },
      {
        key: "copy-link",
        action: handleCopyText,
        title: t("Copy link"),
        icon: LinkIcon,
      },
      {
        key: "delete",
        action: handleDelete,
        title: t("Delete"),
        icon: TrashIcon,
      },
    ],
    [handleEdit, handleOpenInNewTab, handleCopyText, handleDelete, t]
  );

  if (!linkDetail) return null;

  return (
    <LinkItemBlock
      title={linkDetail.title || linkDetail.url}
      url={linkDetail.url}
      createdAt={linkDetail.created_at}
      menuItems={menuItems}
      onClick={handleOpenInNewTab}
    />
  );
});
