import { forwardRef, type SelectHTMLAttributes, type ReactNode } from 'react'
import { cv, type VariantProps } from '../../lib/cv.js'
import { formControlBase, formControlState } from './form-control.js'

const select = cv(`${formControlBase} appearance-none pr-8`, {
  variants: {
    size: {
      sm: 'py-1.5 pr-7 pl-3 text-[length:var(--fs-sub)]',
      md: '',
      lg: 'py-2.5 pr-9 pl-3',
    },
    state: {
      default: formControlState.default,
      invalid: formControlState.invalid,
      valid: formControlState.valid,
    },
  },
  defaultVariants: { size: 'md', state: 'default' },
})

export type SelectVariants = VariantProps<typeof select>

export interface SelectProps
  extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'>, SelectVariants {
  children?: ReactNode
}

export const Select = forwardRef<HTMLSelectElement, SelectProps>(function Select(
  { size, state, className, children, ...rest },
  ref,
) {
  return (
    <div className="relative">
      <select ref={ref} className={select({ size, state, class: className })} {...rest}>
        {children}
      </select>
      <svg
        aria-hidden
        className="pointer-events-none absolute top-1/2 right-2 h-4 w-4 -translate-y-1/2 text-[var(--muted)]"
        viewBox="0 0 20 20"
        fill="currentColor"
      >
        <path
          fillRule="evenodd"
          d="M5.23 7.21a.75.75 0 011.06.02L10 11.06l3.71-3.83a.75.75 0 111.08 1.04l-4.25 4.39a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z"
          clipRule="evenodd"
        />
      </svg>
    </div>
  )
})

export { select as selectVariants }
