/**
 * 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";

// plane types
import type { TInboxIssueFilterMemberKeys } from "@plane/types";
// plane ui
import { Avatar } from "@plane/ui";
// helpers
import { getFileURL } from "@plane/utils";
// hooks
import { useMember } from "@/hooks/store/use-member";
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { InboxAppliedFilterChip } from "./chip";

type InboxIssueAppliedFiltersMember = {
  filterKey: TInboxIssueFilterMemberKeys;
  label: string;
};

export const InboxIssueAppliedFiltersMember = observer(function InboxIssueAppliedFiltersMember(
  props: InboxIssueAppliedFiltersMember
) {
  const { filterKey, label } = props;
  // hooks
  const { inboxFilters, handleInboxIssueFilters } = useProjectInbox();
  const { getUserDetails } = useMember();
  // derived values
  const filteredValues = inboxFilters?.[filterKey] || [];
  const currentOptionDetail = (memberId: string) => getUserDetails(memberId) || undefined;

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

  const clearFilter = () => handleInboxIssueFilters(filterKey, undefined);

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

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

      return {
        key: value,
        label: optionDetail.display_name,
        icon: (
          <Avatar
            name={optionDetail.display_name}
            src={getFileURL(optionDetail.avatar_url)}
            showTooltip={false}
            size="sm"
          />
        ),
        onRemove: () => handleInboxIssueFilters(filterKey, handleFilterValue(value)),
      };
    })
    .filter((value): value is NonNullable<typeof value> => !!value);

  return (
    <InboxAppliedFilterChip title={label} values={values} onClear={clearFilter} />
  );
});
