import React from 'react';
import {
  Tag as AriaTag,
  TagGroup as AriaTagGroup,
  TagGroupProps as AriaTagGroupProps,
  TagProps as AriaTagProps,
  Button,
  TagList as RACTagList,
  TagListProps,
  composeRenderProps,
} from 'react-aria-components';
import { twMerge } from 'tailwind-merge';
import { composeTailwindRenderProps } from './tw-utils';
import { CloseIcon } from '@trail-ui/icons';

export interface TagProps extends AriaTagProps {
  children: React.ReactNode;
}

export function TagGroup({ children, ...props }: AriaTagGroupProps) {
  return (
    <AriaTagGroup {...props} className={twMerge('flex flex-col gap-1', props.className)}>
      {children}
    </AriaTagGroup>
  );
}

export function TagList<T extends object>(props: TagListProps<T>) {
  return (
    <RACTagList
      {...props}
      className={composeTailwindRenderProps(props.className, 'flex flex-wrap gap-1')}
    />
  );
}

export function Tag({ children, ...props }: TagProps) {
  const textValue = typeof children === 'string' ? children : undefined;

  return (
    <AriaTag
      {...props}
      textValue={textValue}
      className={composeRenderProps(props.className, (className, renderProps) => {
        return twMerge(
          'flex h-6 max-w-fit cursor-default items-center gap-0.5 rounded border border-neutral-800 bg-neutral-200 px-2 text-xs text-neutral-950 transition',
          renderProps.allowsRemoving && 'pe-1',
          renderProps.isFocused && ['outline-offset-1 outline-purple-600'],
          className,
        );
      })}
    >
      {({ allowsRemoving }) => {
        return (
          <>
            {children}
            {allowsRemoving && (
              <Button
                slot="remove"
                className="flex cursor-pointer items-center justify-center rounded-full outline-0"
              >
                <CloseIcon height={16} width={16} />
              </Button>
            )}
          </>
        );
      }}
    </AriaTag>
  );
}
