const { h, matter, preactHooks } = globalThis.ami
const { useState } = preactHooks // Preact hooks

export function Checkbox ({ field }) {
  const isRequired = field.required === '1'
  const label = isRequired ? `${field.label} *` : field.label
  // Mark as required only if no box is checked.
  const [isMarkedRequired, setIsMarkedRequired] = useState(isRequired)
  let id = 1

  return h('fieldset', { className: 'block space-y-1' },
    h('legend', { className: 'block font-bold' }, label),
    field.options.map((option, index) =>
      h('label', { className: 'space-x-2 flex items-center cursor-pointer' },
        h(matter.Input, {
          ...field.attrs,
          id: `${field.attrs.id}_${id++}`,
          type: 'checkbox',
          name: null,
          value: option.value,
          required: (index === 0) && isMarkedRequired,
          'data-label': field.label,
          onChange (event) {
            // Set value of the hidden field.
            const fieldset = event.currentTarget.closest('fieldset')
            const values = [...fieldset.querySelectorAll('input[type="checkbox"')]
              .map(input => input.checked ? input.value : null)
            const value = values
              .filter(v => v != null)
              .join('\n')

            fieldset.querySelector('input[type="hidden"]').value = value
            setIsMarkedRequired(isRequired && !values.some(Boolean))
          }
        }),
        h('span', option.label)
      )
    ),
    h(matter.Input, { type: 'hidden', name: field.attrs.name }),
    field.description && h('span', { className: 'text-sm' }, field.description)
  )
}
