'use client'

import type { ComponentProps } from 'react'

import type { GDSComponentProps } from '@graphprotocol/gds-css'

import { useCSSPropsPolyfill, useGDS } from '../hooks/index.ts'
import { cn, getCSSPropsAttributes } from '../utils/index.ts'
import { renderAddon, type AddonValue } from './base/Addon.tsx'
import { TagMeta } from './Tag.meta.ts'

export interface TagProps extends ComponentProps<'span'>, GDSComponentProps<typeof TagMeta> {
  addonBefore?: AddonValue | undefined
}

export function Tag({
  ref: passedRef,
  variant,
  size,
  addonBefore,
  className,
  style,
  children,
  ...props
}: TagProps) {
  useGDS()

  const [cssPropsPolyfillPassedRef, cssPropsPolyfillAttributes] = useCSSPropsPolyfill(
    TagMeta,
    { variant, size },
    { ref: passedRef },
  )

  return (
    <span
      ref={cssPropsPolyfillPassedRef}
      className={cn('gds-tag root-block u:w-max u:max-w-full i:h-max', className)}
      {...getCSSPropsAttributes(TagMeta, { variant, size }, style)}
      {...cssPropsPolyfillAttributes}
      {...props}
    >
      <span
        className={`
          flex h-(--height) min-w-(--height) items-center justify-center rounded-full px-(--gds-tag-padding)
          text-center text-white transition
          @prop-variant-muted/tag:bg-muted
          @prop-variant-muted/tag:text-default
          @prop-variant-brand/tag:bg-brand-muted
          @prop-variant-galactic/tag:bg-status-info-muted
          @prop-variant-starfield/tag:bg-status-success-muted
          @prop-variant-solar/tag:bg-status-warning-muted
          @prop-variant-sonja/tag:bg-status-error-muted
          @prop-variant-elevated/tag:bg-elevated
          @prop-variant-elevated/tag:text-default
          @prop-size-xsmall/tag:[--height:--spacing(4)]
          @prop-size-small/tag:[--height:--spacing(5)]
          @prop-size-medium/tag:[--height:--spacing(6)]
          u:@prop-size-xsmall/tag:addon-small
          u:@prop-size-small/tag:addon-small
          u:@prop-size-medium/tag:addon-medium
        `}
      >
        {addonBefore ? (
          <TagAddon
            className={`
              @prop-size-xsmall/tag:-ms-0.5
              @prop-size-small/tag:-ms-0.5
              @prop-size-medium/tag:-ms-1
            `}
          >
            {renderAddon(addonBefore)}
          </TagAddon>
        ) : null}
        <span
          className={`
            truncate px-0.5
            @prop-size-xsmall/tag:text-10
            @prop-size-small/tag:text-10
            @prop-size-medium/tag:text-12
          `}
        >
          {children}
        </span>
      </span>
    </span>
  )
}

function TagAddon({ className, children, ...props }: ComponentProps<'span'>) {
  return (
    <span
      className={cn(
        'gds-addon root-flex items-center justify-center u:h-(--gds-addon-size) u:min-w-(--gds-addon-size) u:shrink-0',
        className,
      )}
      {...props}
    >
      {children}
    </span>
  )
}
