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

import { observer } from "mobx-react";
import { ISSUE_PRIORITIES } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { PriorityIcon } from "@plane/propel/icons";
import type { TIssuePriorities } from "@plane/types";
// hooks
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { InboxAppliedFilterChip } from "./chip";

export const InboxIssueAppliedFiltersPriority = observer(function InboxIssueAppliedFiltersPriority() {
  // hooks
  const { t } = useTranslation();
  const { inboxFilters, handleInboxIssueFilters } = useProjectInbox();
  // derived values
  const filteredValues = inboxFilters?.priority || [];
  const currentOptionDetail = (priority: TIssuePriorities) =>
    ISSUE_PRIORITIES.find((p) => p.key === priority) || undefined;

  const handleFilterValue = (value: TIssuePriorities): TIssuePriorities[] =>
    filteredValues?.includes(value) ? filteredValues.filter((v) => v !== value) : [...filteredValues, value];

  const clearFilter = () => handleInboxIssueFilters("priority", undefined);

  if (filteredValues.length === 0) return <></>;

  const values = filteredValues
    .map((value) => {
      const optionDetail = currentOptionDetail(value);
      if (!optionDetail) return undefined;

      return {
        key: value,
        label: optionDetail.title,
        icon: <PriorityIcon priority={optionDetail.key} className="h-3 w-3" />,
        onRemove: () => handleInboxIssueFilters("priority", handleFilterValue(optionDetail.key)),
      };
    })
    .filter((value): value is NonNullable<typeof value> => !!value);

  return (
    <InboxAppliedFilterChip title={t("common.priority")} values={values} onClear={clearFilter} />
  );
});
