import { Box, Tag as TagComponent } from '@wix/design-system';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import React, { useState } from 'react';
import { Tag } from '@wix/bex-utils/@wix/ambassador-os-tags-v1-tag/types';
import { observer } from 'mobx-react-lite';
import { Tags } from '@wix/bex-core';

const MAX_VISIBLE_TAGS = 3;

export interface KanbanCardTagsProps<T> {
  item: T;
  /**
   * Data hook for the tags container
   */
  dataHook?: string;
  /**
   * Maximum number of tags to show before collapsing
   * @default 3
   */
  maxVisibleTags?: number;
}

function _KanbanCardTags<T>({
  item,
  dataHook,
  maxVisibleTags = MAX_VISIBLE_TAGS,
}: KanbanCardTagsProps<T>) {
  const { tagsCollectionState } = useToolbarCollectionContext();
  const [isExpanded, setIsExpanded] = useState(false);

  if (!tagsCollectionState?.tagsManagementState) {
    return null;
  }

  const tags: Tags | undefined =
    tagsCollectionState._getTags?.(item) ?? (item as { tags?: Tags }).tags;

  if (!tags?.privateTags?.tagIds?.length) {
    return null;
  }

  const tagItems = tags.privateTags.tagIds
    .map((tagId: string) =>
      tagsCollectionState.tagsManagementState.items.find(
        (tag: Tag) => tag.id === tagId,
      ),
    )
    .filter(Boolean) as Tag[];

  if (tagItems.length === 0) {
    return null;
  }

  const visibleTags = isExpanded ? tagItems : tagItems.slice(0, maxVisibleTags);
  const hiddenCount = tagItems.length - maxVisibleTags;
  const hasMoreTags = hiddenCount > 0;

  return (
    <Box
      dataHook={dataHook}
      direction="horizontal"
      gap="tiny"
      verticalAlign="middle"
      flexWrap="wrap"
      marginTop="6px"
    >
      {visibleTags.map((tag) => (
        <TagComponent
          key={tag.id}
          id={tag.id!}
          dataHook={`${dataHook}-${tag.id}`}
          size="tiny"
          removable={false}
        >
          {tag.name}
        </TagComponent>
      ))}
      {hasMoreTags && !isExpanded && (
        <TagComponent
          id={`${dataHook}-toggle`}
          dataHook={`${dataHook}-toggle`}
          size="tiny"
          removable={false}
          onClick={() => setIsExpanded(!isExpanded)}
          skin="lightOutlined"
        >
          {`+${hiddenCount}`}
        </TagComponent>
      )}
    </Box>
  );
}

export const KanbanCardTags = observer(_KanbanCardTags);
