/**
 * 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";
// hooks
import { useTranslation } from "@plane/i18n";
import { useLabel } from "@/hooks/store/use-label";
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { InboxAppliedFilterChip } from "./chip";

function LabelIcons({ color }: { color: string }) {
  return <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: color }} />;
}

export const InboxIssueAppliedFiltersLabel = observer(function InboxIssueAppliedFiltersLabel() {
  const { t } = useTranslation();
  // hooks
  const { inboxFilters, handleInboxIssueFilters } = useProjectInbox();
  const { getLabelById } = useLabel();
  // derived values
  const filteredValues = inboxFilters?.labels || [];
  const currentOptionDetail = (labelId: string) => getLabelById(labelId) || undefined;

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

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

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

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

      return {
        key: value,
        label: optionDetail.name,
        icon: <LabelIcons color={optionDetail.color} />,
        onRemove: () => handleInboxIssueFilters("labels", handleFilterValue(value)),
      };
    })
    .filter((value): value is NonNullable<typeof value> => !!value);

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