/**
 * 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 { EIconSize } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { StateGroupIcon } from "@plane/propel/icons";
// hooks
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { useProjectState } from "@/hooks/store/use-project-state";
import { InboxAppliedFilterChip } from "./chip";

export const InboxIssueAppliedFiltersState = observer(function InboxIssueAppliedFiltersState() {
  const { t } = useTranslation();
  // hooks
  const { inboxFilters, handleInboxIssueFilters } = useProjectInbox();
  const { getStateById } = useProjectState();
  // derived values
  const filteredValues = inboxFilters?.state || [];
  const currentOptionDetail = (stateId: string) => getStateById(stateId) || undefined;

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

  const clearFilter = () => handleInboxIssueFilters("state", 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: <StateGroupIcon color={optionDetail.color} stateGroup={optionDetail.group} size={EIconSize.SM} />,
        onRemove: () => handleInboxIssueFilters("state", handleFilterValue(optionDetail.id)),
      };
    })
    .filter((value): value is NonNullable<typeof value> => !!value);

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