import styled from "@emotion/styled"
import { token, vars } from "~/options/theme"
import { useEvent } from "@aet/hooks"

export interface TagRender {
  (props: { Tag: typeof Tag; defaultProps: TagProps; tag: string }): React.ReactNode
}

export const defaultTagRender: TagRender = ({ Tag, tag, defaultProps }) => (
  <Tag key={tag} {...defaultProps} />
)

interface TagProps extends React.HTMLAttributes<HTMLSpanElement> {
  text: string
  remove: (text: string) => void
  disabled?: boolean
  className?: string
}

export function Tag({ text, remove, disabled, ...props }: TagProps) {
  const handleOnRemove: React.MouseEventHandler<HTMLButtonElement> = useEvent(e => {
    e.stopPropagation()
    remove(text)
  })

  return (
    <TagContainer {...props}>
      <span>{text}</span>
      {!disabled && (
        <Button type="button" onClick={handleOnRemove} aria-label={`Remove ${text}`}>
          &#10005;
        </Button>
      )}
    </TagContainer>
  )
}

const TagContainer = styled.span`
  align-items: center;
  background: ${vars.backgroundActive};
  border-radius: 0.375rem;
  display: inline-flex;
  justify-content: center;
  padding: 0.15rem 0.25rem;
  padding-left: 0.6rem;
  user-select: none;
  &:hover {
    background-color: ${token.canvas.overlay};
    color: unset;
  }
`

const Button = styled.button`
  background: none;
  border: 0;
  border-radius: 50%;
  cursor: pointer;
  line-height: inherit;
  padding: 0 0.5rem;

  &:hover {
    color: #e53e3e;
  }
`
