import { CheckIcon, Cross1Icon } from '@radix-ui/react-icons'

import { cva, type VariantProps } from 'class-variance-authority'

import { cn } from '@lib/utils'

type CheckboxProps = React.ComponentProps<'input'> &
  VariantProps<typeof checkboxVariants> & {
    label?: string
    /**
     * E2E test_id to identify the checkbox.
     */
    __e2e_test_id__?: string
  }

const checkboxVariants = cva(
  'cursor-pointer peer appearance-none rounded border focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive shrink-0 shadow-xs transition-shadow',
  {
    variants: {
      variant: {
        default: '',
        simple: ' border-input checked:bg-muted-foreground checked:border-muted-foreground',
        iconSolo: 'border-transparent shadow-none',
      },
      checkboxSize: {
        default: 'size-4 [&_svg]:size-3.5',
        sm: 'size-3.5 [&_svg]:size-3',
        lg: 'size-4.5 [&_svg]:size-4',
      },
      checkIcon: {
        default: 'cross',
        check: 'check',
      },
      iconStyle: {
        default: 'text-foreground',
        simple: 'text-primary-foreground',
        solo: 'text-muted-foreground shadow-none',
      },
    },
    defaultVariants: {
      variant: 'default',
      checkIcon: 'default',
      iconStyle: 'default',
      checkboxSize: 'default',
    },
  },
)

function Checkbox({
  label,
  className,
  variant,
  checkIcon,
  checkboxSize,
  iconStyle,
  __e2e_test_id__,
  ...props
}: CheckboxProps) {
  const inputId = props.id ?? (label ? `${label}-checkbox` : undefined)

  return (
    <div className={cn('relative flex gap-2 items-center', className)} data-test-id={__e2e_test_id__}>
      <input {...props} type="checkbox" id={inputId} className={cn(checkboxVariants({ variant, checkboxSize }))} />
      <span
        className={cn(
          checkboxVariants({ iconStyle, checkboxSize }),
          'absolute opacity-0 peer-checked:opacity-100 top-1/2 left-0 transform -translate-y-1/2 pointer-events-none flex items-center justify-center border-transparent',
        )}
      >
        {checkIcon === 'check' ? <CheckIcon /> : <Cross1Icon />}
      </span>
      <label htmlFor={inputId} className="cursor-pointer select-none">
        {label}
      </label>
    </div>
  )
}

export { Checkbox, checkboxVariants }
