'use client'
import type { QuestionOption } from '@/lib/types'

interface CheckboxGroupProps {
  name: string
  legend: string
  options: QuestionOption[]
  value: string[]
  maxSelect: number | null
  required: boolean
  onChange: (value: string[]) => void
  error?: string
}

export function CheckboxGroup({
  name,
  legend,
  options,
  value,
  maxSelect,
  required,
  onChange,
  error,
}: CheckboxGroupProps) {
  const atLimit = maxSelect !== null && value.length >= maxSelect

  function toggle(optValue: string) {
    if (value.includes(optValue)) {
      onChange(value.filter((v) => v !== optValue))
    } else if (!atLimit) {
      onChange([...value, optValue])
    }
  }

  return (
    <fieldset className="question-fieldset">
      <legend className="question-legend">
        {legend}
        {required && <span className="required-mark" aria-hidden="true"> *</span>}
        {required && <span className="sr-only"> (obligatorio)</span>}
      </legend>
      {maxSelect !== null && (
        <p className="max-select-hint" aria-live="polite">
          Elegí hasta {maxSelect} opciones
          {value.length > 0 && ` · ${value.length}/${maxSelect} seleccionadas`}
        </p>
      )}
      <div className="options-list" role="list">
        {options.map((opt) => {
          const id = `${name}_${opt.value.replace(/\s+/g, '_')}`
          const checked = value.includes(opt.value)
          const disabled = atLimit && !checked

          return (
            <div key={opt.value} className="option-item" role="listitem">
              <label
                className={`option-label${disabled ? ' option-disabled' : ''}`}
                htmlFor={id}
              >
                <input
                  type="checkbox"
                  id={id}
                  name={name}
                  value={opt.value}
                  checked={checked}
                  disabled={disabled}
                  onChange={() => toggle(opt.value)}
                  aria-required={required}
                  aria-disabled={disabled}
                  className="option-input"
                />
                <span className="option-text">{opt.label}</span>
              </label>
            </div>
          )
        })}
      </div>
      {error && (
        <p role="alert" className="field-error" id={`${name}-error`}>
          {error}
        </p>
      )}
    </fieldset>
  )
}
