/**
 * 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 { INBOX_STATUS } from "@plane/constants";
import { useTranslation } from "@plane/i18n";
import { EInboxIssueStatus, type TInboxIssueStatus } from "@plane/types";
// constants
// hooks
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { InboxStatusIcon } from "../../inbox-status-icon";
import { InboxAppliedFilterChip } from "./chip";

export const InboxIssueAppliedFiltersStatus = observer(function InboxIssueAppliedFiltersStatus() {
  // hooks
  const { inboxFilters, handleInboxIssueFilters } = useProjectInbox();
  const { t } = useTranslation();
  // derived values
  const filteredValues = inboxFilters?.status || [];
  const shouldHideDefaultOpenFilter =
    filteredValues.length === 1 && filteredValues[0] === EInboxIssueStatus.PENDING;
  const currentOptionDetail = (status: TInboxIssueStatus) => INBOX_STATUS.find((s) => s.status === status) || undefined;

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

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

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

      return {
        key: String(value),
        label: t(optionDetail.i18n_title),
        icon: <InboxStatusIcon type={optionDetail.status} className="h-3.5 w-3.5" />,
        onRemove:
          handleFilterValue(optionDetail.status).length >= 1
            ? () => handleInboxIssueFilters("status", handleFilterValue(optionDetail.status))
            : undefined,
      };
    })
    .filter((value): value is NonNullable<typeof value> => !!value);

  return (
    <InboxAppliedFilterChip
      title="Status"
      values={values}
      onClear={() => handleInboxIssueFilters("status", [EInboxIssueStatus.PENDING] as TInboxIssueStatus[])}
    />
  );
});
