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

import { observer } from "mobx-react";
import { History } from "lucide-react";
// pi dash imports
import { useTranslation } from "@pi-dash/i18n";
import type { TDescriptionVersion } from "@pi-dash/types";
import { CustomMenu } from "@pi-dash/ui";
import { calculateTimeAgo } from "@pi-dash/utils";
// hooks
import { useMember } from "@/hooks/store/use-member";
// local imports
import { DescriptionVersionsDropdownItem } from "./dropdown-item";
import type { TDescriptionVersionEntityInformation } from "./root";

type Props = {
  disabled: boolean;
  entityInformation: TDescriptionVersionEntityInformation;
  onVersionClick: (versionId: string) => void;
  versions: TDescriptionVersion[] | undefined;
};

export const DescriptionVersionsDropdown = observer(function DescriptionVersionsDropdown(props: Props) {
  const { disabled, entityInformation, onVersionClick, versions } = props;
  // store hooks
  const { getUserDetails } = useMember();
  // derived values
  const latestVersion = versions?.[0];
  const lastUpdatedAt = latestVersion?.created_at ?? entityInformation.createdAt;
  const lastUpdatedByUserDisplayName = latestVersion?.owned_by
    ? getUserDetails(latestVersion?.owned_by)?.display_name
    : entityInformation.createdByDisplayName;
  // translation
  const { t } = useTranslation();

  return (
    <CustomMenu
      label={
        <div className="flex items-center gap-1 text-tertiary">
          <span className="grid size-4 flex-shrink-0 place-items-center">
            <History className="size-3.5" />
          </span>
          <p className="text-11">
            {t("Last edited by")}{" "}
            <span className="font-medium">{lastUpdatedByUserDisplayName ?? t("Deactivated user")}</span>{" "}
            {calculateTimeAgo(lastUpdatedAt)}
            {entityInformation.isExternallySynced ? (
              <span className="ml-1 text-tertiary">
                ({t("edit disabled for external import issue") || "edit disabled for external import issue"})
              </span>
            ) : null}
          </p>
        </div>
      }
      noBorder
      noChevron={disabled}
      placement="bottom-end"
      optionsClassName="w-[300px]"
      disabled={disabled}
      closeOnSelect
    >
      <p className="mb-1 text-11 font-medium text-tertiary">{t("Previously edited by")}</p>
      {versions?.map((version) => (
        <DescriptionVersionsDropdownItem key={version.id} onClick={onVersionClick} version={version} />
      ))}
    </CustomMenu>
  );
});
