'use client';

import * as React from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check } from 'lucide-react';

import { cn } from '../../shared/utils';

/**
 * Accessible boolean or multi-select checkbox built on Radix UI.
 *
 * @description
 * Used to capture multiple-choice selections or a single boolean toggle
 * (e.g., "Accept terms and conditions").
 * Supports the standard size scale (`sm`, `md`, `lg`) for consistent form alignment.
 *
 * @ai-rules
 * 1. NEVER use a native `<input type="checkbox">`.
 * 2. Always pair with a real `<label>` using matching `id` and `htmlFor` props.
 * 3. Inside React Hook Form schemas, wrap in `<FormControl>` within a `<FormField>`.
 * 4. Use the `size` prop to match surrounding form element sizing.
 */
const Checkbox = React.forwardRef<
  React.ElementRef<typeof CheckboxPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> & {
    /**
     * Size variant — matches the form component sizing scale.
     * - `sm`: 14px square
     * - `md`: 16px square — **default**
     * - `lg`: 20px square
     */
    size?: 'sm' | 'md' | 'lg';
  }
>(({ className, size = 'md', ...props }, ref) => {
  const sizeClasses = {
    sm: 'size-3.5',
    md: 'size-4',
    lg: 'size-5',
  };
  const iconSizeClasses = {
    sm: 'size-3',
    md: 'size-3.5',
    lg: 'size-4',
  };

  return (
    <CheckboxPrimitive.Root
      ref={ref}
      data-slot="checkbox"
      className={cn(
        'peer border bg-white dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary 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 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
        sizeClasses[size],
        className
      )}
      {...props}
    >
      <CheckboxPrimitive.Indicator
        data-slot="checkbox-indicator"
        className="flex items-center justify-center text-current transition-none"
      >
        <Check className={iconSizeClasses[size]} />
      </CheckboxPrimitive.Indicator>
    </CheckboxPrimitive.Root>
  );
});
Checkbox.displayName = CheckboxPrimitive.Root.displayName;

export { Checkbox };
