import * as React from 'react'
import * as CheckboxPrimitive from '@radix-ui/react-checkbox'
import { Check, Minus } from 'lucide-react'
import { cn } from '@/lib/utils'

/**
 * Checkbox — Radix primitive с nstart-compat label / description / onChange API.
 *
 * <p>Поддерживает три формы:
 * <ol>
 *   <li>Bare: {@code <Checkbox checked={c} onCheckedChange={setC} />} — Radix native.</li>
 *   <li>nstart-style: {@code <Checkbox label="..." checked={c} onChange={(e) =>
 *       setC(e.target.checked)} />} — wraps в &lt;label&gt; с описанием.</li>
 *   <li>Indeterminate: {@code checked="indeterminate"} (Radix tri-state).</li>
 * </ol>
 *
 * <p>onChange синтезирует {@code ChangeEvent<HTMLInputElement>}-like shape с
 * {@code target.checked} для существующего кода (был nstart compatibility).
 */

type RadixCheckboxProps = React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>

export type CheckboxProps = Omit<RadixCheckboxProps, 'onChange'> & {
  label?: React.ReactNode
  description?: React.ReactNode
  /** Error message shown под label (nstart-compat). */
  error?: React.ReactNode
  /** nstart-style change handler. Synthetic event с {@code target.checked}. */
  onChange?: (e: { target: { checked: boolean } }) => void
}

export const Checkbox = React.forwardRef<
  React.ElementRef<typeof CheckboxPrimitive.Root>,
  CheckboxProps
>(function Checkbox(
  { className, label, description, error, onChange, onCheckedChange, ...props },
  ref,
) {
  const autoId = React.useId()
  const id = props.id ?? autoId
  const handleCheckedChange = (next: boolean | 'indeterminate') => {
    onCheckedChange?.(next)
    if (onChange && typeof next === 'boolean') {
      onChange({ target: { checked: next } })
    }
  }

  const root = (
    <CheckboxPrimitive.Root
      ref={ref}
      id={id}
      onCheckedChange={handleCheckedChange}
      className={cn(
        'peer h-4 w-4 shrink-0 rounded-[3px] border border-line bg-surface',
        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1',
        'disabled:cursor-not-allowed disabled:opacity-50',
        'data-[state=checked]:bg-accent data-[state=checked]:border-accent data-[state=checked]:text-on-accent',
        'data-[state=indeterminate]:bg-accent data-[state=indeterminate]:border-accent data-[state=indeterminate]:text-on-accent',
        className,
      )}
      {...props}
    >
      <CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
        {props.checked === 'indeterminate' ? (
          <Minus size={11} strokeWidth={3} />
        ) : (
          <Check size={11} strokeWidth={3} />
        )}
      </CheckboxPrimitive.Indicator>
    </CheckboxPrimitive.Root>
  )

  if (!label && !description && !error) return root

  return (
    <label htmlFor={id} className="inline-flex items-start gap-2 cursor-pointer select-none">
      {root}
      <span className="flex flex-col gap-0.5 min-w-0">
        {label && <span className="text-body text-ink">{label}</span>}
        {description && <span className="text-cell text-mute">{description}</span>}
        {error && <span className="text-cell text-pink" role="alert">{error}</span>}
      </span>
    </label>
  )
})
