const { h, register, matter, preactHooks } = globalThis.ami
const { useState } = preactHooks
const { Input, Box, Form, Button } = matter

function ExampleForm (props) {
  const [submitted, setSubmitted] = useState(false)

  const onSubmit = event => {
    event.preventDefault()
    setSubmitted(true)
  }

  if (submitted) {
    return h(Box, { className: 'bg-bga text-txa rounded-2xl' }, 'Thank you for submitting the form.')
  }

  const options = [
    h('option'),
    h('option', 'A'),
    h('option', 'B'),
    h('option', 'C'),
  ]

  return h(Form, { name: 'Example form', onSubmit },
    h(Box, { ...props, className: 'bg-bga text-txa rounded-2xl' },
      h('div', { className: 'grid grid-cols-2 gap-4' },
        h('div', { className: 'space-y-4' },
          h(Field, { label: 'Required input', required: true }),
          h(Field, { type: 'select', label: 'Required select', required: true, children: options }),
          h(Field, { type: 'textarea', label: 'Required textarea', required: true }),
          h(Field, { type: 'checkbox', label: 'Required checkbox', required: true }),
          h(Field, { type: 'radio', label: 'Required radio', required: true })
        ),
        h('div', { className: 'space-y-4' },
          h(Field, { label: 'Disabled input', disabled: true }),
          h(Field, { type: 'select', label: 'Disabled select', disabled: true, children: options }),
          h(Field, { type: 'textarea', label: 'Disabled textarea', disabled: true }),
          h(Field, { type: 'checkbox', label: 'Disabled checkbox', disabled: true }),
          h(Field, { type: 'radio', label: 'Disabled radio', disabled: true }),
          h(Field, { type: 'file', label: 'Disabled file', disabled: true })
        )
      ),
      h(Button, { type: 'submit', _model: { name: 'Submit' } })
    )
  )
}

function Field ({ type, label, required, disabled, children }) {
  const fullLabel = required ? `${label} *` : label

  return h('label', { className: 'block' },
    h('span', { className: 'font-bold' }, fullLabel),
    h('div',
      h(Input, { type, 'data-label': label, required, disabled, children })
    )
  )
}

register(ExampleForm, 'example-form')
