import { type FormEvent, useState } from 'react'
import { ApiHttpError } from '../../api/http'
import { postInventoryCategory } from '../../api/inventory'

type Props = {
  modalId: string
  inventoryType: 'book' | 'classroom' | 'kitchen' | 'office'
  title: string
  includeGradeRange?: boolean
  onSaved?: () => void
}

export function CategoryAddModal({
  modalId,
  inventoryType,
  title,
  includeGradeRange,
  onSaved,
}: Props) {
  const [error, setError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    const fd = new FormData(e.currentTarget)
    try {
      await postInventoryCategory({
        type: inventoryType,
        name: fd.get('name'),
        description: fd.get('description') || undefined,
        grade_min: fd.get('grade_min') === '' ? undefined : Number(fd.get('grade_min')),
        grade_max: fd.get('grade_max') === '' ? undefined : Number(fd.get('grade_max')),
      })
      onSaved?.()
      e.currentTarget.reset()
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="modal fade" id={modalId} tabIndex={-1} aria-hidden="true">
      <div className="modal-dialog">
        <form className="modal-content" onSubmit={(ev) => void onSubmit(ev)}>
          <div className="modal-header">
            <h5 className="modal-title">{title}</h5>
            <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close" />
          </div>
          <div className="modal-body">
            {error ? <div className="alert alert-danger py-2 small">{error}</div> : null}
            <div className="mb-3">
              <label className="form-label">Name</label>
              <input type="text" name="name" className="form-control" required />
            </div>
            {includeGradeRange ? (
              <div className="row g-2 mb-3">
                <div className="col-6">
                  <label className="form-label">Grade Min</label>
                  <input
                    type="number"
                    name="grade_min"
                    className="form-control"
                    min={0}
                    max={13}
                    placeholder="e.g., 1"
                  />
                </div>
                <div className="col-6">
                  <label className="form-label">Grade Max</label>
                  <input
                    type="number"
                    name="grade_max"
                    className="form-control"
                    min={0}
                    max={13}
                    placeholder="e.g., 3"
                  />
                </div>
                <div className="col-12">
                  <small className="text-muted">Optional. Used for book categories.</small>
                </div>
              </div>
            ) : null}
            <div className="mb-0">
              <label className="form-label">Description (optional)</label>
              <textarea name="description" className="form-control" rows={2} />
            </div>
          </div>
          <div className="modal-footer">
            <button type="button" className="btn btn-outline-secondary" data-bs-dismiss="modal">
              Close
            </button>
            <button type="submit" className="btn btn-primary" disabled={saving}>
              {saving ? 'Saving…' : 'Save Category'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
