import { useState } from 'react'

const inputStyle: React.CSSProperties = {
  background: 'var(--color-bg2)',
  color: 'var(--color-fg)',
  borderColor: 'var(--color-bg3)',
}

interface Props {
  onAdd: (id: string, label: string, required: boolean) => void
  onClose: () => void
}

export function AddSectionDialog({ onAdd, onClose }: Props) {
  const [label, setLabel] = useState('')
  const [required, setRequired] = useState(false)

  function submit(e: React.FormEvent) {
    e.preventDefault()
    const id = label.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
    onAdd(id, label, required)
    onClose()
  }

  const inputCls = 'w-full rounded border px-2 py-1.5 text-sm outline-none'

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: 'rgba(0,0,0,0.6)' }}
      onClick={e => e.target === e.currentTarget && onClose()}
    >
      <div
        className="w-full max-w-sm rounded-lg border p-0"
        style={{ background: 'var(--color-bg1)', borderColor: 'var(--color-bg3)', color: 'var(--color-fg)' }}
      >
        <form onSubmit={submit}>
          <div className="flex items-center justify-between border-b px-4 py-3" style={{ borderColor: 'var(--color-bg3)' }}>
            <h2 className="font-medium">Add section</h2>
            <button type="button" onClick={onClose} style={{ color: 'var(--color-grey)' }}>✕</button>
          </div>

          <div className="flex flex-col gap-4 p-4">
            <div className="flex flex-col gap-1">
              <label className="text-xs" style={{ color: 'var(--color-grey)' }}>Label *</label>
              <input
                required
                value={label}
                onChange={e => setLabel(e.target.value)}
                className={inputCls}
                style={inputStyle}
                placeholder="e.g. Goggles"
              />
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input type="checkbox" checked={required} onChange={e => setRequired(e.target.checked)} />
              <span style={{ color: 'var(--color-grey)' }}>Required (can't fly without this)</span>
            </label>
          </div>

          <div className="flex justify-end gap-2 border-t px-4 py-3" style={{ borderColor: 'var(--color-bg3)' }}>
            <button type="button" onClick={onClose} className="rounded px-3 py-1.5 text-sm" style={{ background: 'var(--color-bg2)', color: 'var(--color-grey)' }}>
              Cancel
            </button>
            <button type="submit" className="rounded px-3 py-1.5 text-sm font-medium" style={{ background: 'var(--color-yellow)', color: 'var(--color-black)' }}>
              Add
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
