import type { JSX } from 'preact';
import { cn } from '../core/cn';

export type CheckboxFieldProps = Omit<JSX.InputHTMLAttributes<HTMLInputElement>, 'type' | 'checked' | 'onChange'> & {
  label: string;
  checked?: boolean;
  boxed?: boolean;
  onCheckedChange?: (checked: boolean) => void;
};

export function CheckboxField({ label, checked, boxed = true, className, required, onCheckedChange, ...props }: CheckboxFieldProps) {
  return (
    <label
      className={cn(
        'ask-checkbox-field ask-flex ask-items-center ask-gap-2 ask-select-none ask-text-[12px] ask-font-medium ask-text-text',
        boxed && 'ask-rounded-xl ask-border ask-border-borderSubtle ask-bg-surface ask-px-3 ask-py-2',
        className,
      )}
    >
      <input
        {...props}
        required={required}
        aria-required={required ? true : undefined}
        type="checkbox"
        className="ask-theme-checkbox"
        checked={checked}
        onChange={(event: any) => onCheckedChange?.(Boolean(event?.currentTarget?.checked))}
      />
      <span>
        {label}
        {required ? (
          <span className="ask-ml-1 ask-text-red-500" aria-hidden="true">
            *
          </span>
        ) : null}
      </span>
    </label>
  );
}
