import { Button } from '../atoms/button.js'
import { Form } from '../atoms/form.js'
import { Heading } from '../atoms/heading.js'
import { Input } from '../atoms/input.js'
import { RichText } from '../atoms/rich-text.js'
import getId from '../shared/get-id.js'
import h from '../shared/h.js'

const DEFAULT_FIELDS = [
  { name: 'name', label: 'Full name', required: true, placeholder: 'Your name' },
  { name: 'email', label: 'Email', type: 'email', required: true, placeholder: 'you@email.com' },
  { name: 'phone', label: 'Phone', type: 'tel', required: true, placeholder: '+91 9XXXXXXXXX' },
  { name: 'city', label: 'City', required: true, placeholder: 'Bengaluru / Seegehalli' },
  { name: 'budget', label: 'Budget range', placeholder: '₹8L - ₹18L' },
  { name: 'message', label: 'Tell us about your home', type: 'textarea', required: true, placeholder: 'Rooms, layout, timelines, and style goals' }
]

function getFields (fields) {
  if (!Array.isArray(fields) || fields.length === 0) {
    return DEFAULT_FIELDS
  }

  return fields
    .filter(field => field?.name)
    .map(field => ({
      type: 'text',
      required: false,
      ...field
    }))
}

function getValueMap (data) {
  const map = {}
  for (const [key, value] of data.entries()) {
    map[key] = value || ''
  }
  return map
}

export function ContactForm ({ _model, ...props }) {
  const {
    title,
    text,
    email,
    to,
    subject,
    endpoint = '/api/contact',
    fields,
    submitLabel = 'Submit enquiry',
    submittingLabel = 'Sending...',
    successMessage = 'Enquiry sent successfully.',
    errorMessage = 'Unable to send enquiry. Please try again.'
  } = _model

  const resolvedFields = getFields(fields)

  const baseId = getId()
  const ids = Object.fromEntries(resolvedFields.map(field => [field.name, `${baseId}-${field.name}`]))

  const onSubmit = async event => {
    event.preventDefault()
    const form = event.currentTarget
    const submitButton = form.querySelector('button[type="submit"]')
    if (submitButton?.disabled) {
      return
    }

    const data = new FormData(event.currentTarget)
    const values = getValueMap(data)
    const payload = {
      to: to || email,
      subject: subject || 'Interior design enquiry',
      replyTo: values.email || '',
      formName: title || 'Contact form',
      fields: values
    }

    const originalLabel = submitButton?.textContent

    try {
      if (submitButton) {
        submitButton.disabled = true
        submitButton.textContent = submittingLabel
      }

      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })

      const result = await response.json().catch(() => ({}))
      if (!response.ok) {
        throw new Error(result.message || 'Unable to send enquiry')
      }

      form.reset()
      globalThis.alert(successMessage)
    } catch (error) {
      globalThis.alert(error.message || errorMessage)
    } finally {
      if (submitButton) {
        submitButton.disabled = false
        submitButton.textContent = originalLabel || submitLabel
      }
    }
  }

  return h('section', { ...props, className: 'bg-bga text-txa rounded-2xl p-6 space-y-5' },
    title && h(Heading, { _level: 2, _size: '6' }, title),
    text && h(RichText, text),
    h(Form, { onSubmit, 'aria-label': title ?? 'Contact form' },
      h('div', { className: 'grid gap-4' },
        ...resolvedFields.map(field => {
          if (field.type === 'hidden') {
            return h(Input, {
              type: 'hidden',
              name: field.name,
              value: field.value ?? ''
            })
          }

          return h('div', { className: 'grid gap-2' },
            h('label', { for: ids[field.name], className: 'text-sm font-bold' }, field.label || field.name),
            h(Input, {
              id: ids[field.name],
              name: field.name,
              type: field.type,
              required: field.required,
              placeholder: field.placeholder,
              value: field.value
            })
          )
        }),
        h('div', { className: 'flex flex-wrap gap-3 items-center' },
          h(Button, { _model: { name: submitLabel }, type: 'submit' }),
        )
      )
    )
  )
}
