import { type FormEvent, useEffect, useState } from 'react'
import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchMovementForm, postMovement, putMovement } from '../../api/inventory'

/** CI `inventory/movements/form.php` + `movements/edit.php` (single React screen). */
export function InventoryMovementFormPage() {
  const { movementId } = useParams()
  const { pathname } = useLocation()
  const [searchParams] = useSearchParams()
  const isCreate = pathname.includes('/create')

  const [movement, setMovement] = useState<Record<string, unknown>>({})
  const [items, setItems] = useState<Record<string, unknown>[]>([])
  const [movementTypes, setMovementTypes] = useState<string[]>([
    'initial',
    'in',
    'out',
    'adjust',
    'distribution',
  ])
  const [semesters, setSemesters] = useState<string[]>(['Fall', 'Spring'])
  const [teachers, setTeachers] = useState<Record<string, unknown>[]>([])
  const [students, setStudents] = useState<Record<string, unknown>[]>([])
  const [classSections, setClassSections] = useState<Record<string, unknown>[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [itemId, setItemId] = useState('')
  const [qtyChange, setQtyChange] = useState('0')
  const [movementType, setMovementType] = useState('adjust')
  const [reason, setReason] = useState('')
  const [note, setNote] = useState('')
  const [semester, setSemester] = useState('')
  const [schoolYear, setSchoolYear] = useState('')
  const [teacherId, setTeacherId] = useState('')
  const [studentId, setStudentId] = useState('')
  const [classSectionId, setClassSectionId] = useState('')

  useEffect(() => {
    let c = false
    setLoading(true)
    fetchMovementForm(isCreate ? undefined : movementId, searchParams)
      .then((data) => {
        if (c) return
        if (data && typeof data === 'object') {
          const o = data as Record<string, unknown>
          if (Array.isArray(o.movementTypes)) {
            setMovementTypes(o.movementTypes as string[])
          }
          if (Array.isArray(o.semesters)) setSemesters(o.semesters as string[])
          if (Array.isArray(o.items)) setItems(o.items as Record<string, unknown>[])
          if (Array.isArray(o.teachers)) setTeachers(o.teachers as Record<string, unknown>[])
          if (Array.isArray(o.students)) setStudents(o.students as Record<string, unknown>[])
          if (Array.isArray(o.classSections)) {
            setClassSections(o.classSections as Record<string, unknown>[])
          }
          const mov = (o.movement ?? {}) as Record<string, unknown>
          setMovement(mov)
          if (!isCreate && mov.id != null) {
            setItemId(String(mov.item_id ?? ''))
            setQtyChange(String(mov.qty_change ?? 0))
            setMovementType(String(mov.movement_type ?? 'adjust'))
            setReason(String(mov.reason ?? ''))
            setNote(String(mov.note ?? ''))
            setSemester(String(mov.semester ?? ''))
            setSchoolYear(String(mov.school_year ?? ''))
            setTeacherId(mov.teacher_id != null ? String(mov.teacher_id) : '')
            setStudentId(mov.student_id != null ? String(mov.student_id) : '')
            setClassSectionId(mov.class_section_id != null ? String(mov.class_section_id) : '')
          }
        }
        setError(null)
      })
      .catch((e: unknown) => {
        if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load form.')
      })
      .finally(() => {
        if (!c) setLoading(false)
      })
    return () => {
      c = true
    }
  }, [isCreate, movementId, searchParams])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    const body: Record<string, unknown> = {
      item_id: itemId === '' ? undefined : Number(itemId),
      qty_change: qtyChange === '' ? 0 : Number(qtyChange),
      movement_type: movementType,
      reason: reason || undefined,
      note: note || undefined,
      semester: semester || undefined,
      school_year: schoolYear || undefined,
      teacher_id: teacherId === '' ? undefined : Number(teacherId),
      student_id: studentId === '' ? undefined : Number(studentId),
      class_section_id: classSectionId === '' ? undefined : classSectionId,
    }
    try {
      if (isCreate) await postMovement(body)
      else await putMovement(movementId ?? '', body)
      window.location.href = '/app/administrator/inventory/movements'
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  const itemLabel =
    String(movement.item_name ?? movement.item_id ?? '') || '—'

  return (
    <div className="container my-4">
      <div className="d-flex justify-content-between align-items-center mb-3">
        <h3 className="mb-0">{isCreate ? 'Create Inventory Movement' : 'Edit Inventory Movement'}</h3>
        <Link className="btn btn-outline-secondary" to="/app/administrator/inventory/movements">
          Back to List
        </Link>
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading ? (
        <form onSubmit={(ev) => void onSubmit(ev)} className="card shadow-sm">
          <div className="card-body">
            <div className="mb-3">
              <label className="form-label">
                Item <span className="text-danger">*</span>
              </label>
              {isCreate ? (
                <select
                  className="form-select"
                  required
                  value={itemId}
                  onChange={(e) => setItemId(e.target.value)}
                >
                  <option value="">-- Select Item --</option>
                  {items.map((it) => (
                    <option key={String(it.id)} value={String(it.id)}>
                      {String(it.name ?? it.id)}
                    </option>
                  ))}
                </select>
              ) : (
                <>
                  <input type="text" className="form-control" value={itemLabel} disabled />
                  <div className="form-text">Item cannot be changed after creation.</div>
                </>
              )}
            </div>

            <div className="row">
              <div className="col-md-6 mb-3">
                <label className="form-label">
                  Quantity Change <span className="text-danger">*</span>
                </label>
                <input
                  type="number"
                  required
                  className="form-control"
                  value={qtyChange}
                  onChange={(e) => setQtyChange(e.target.value)}
                />
                <div className="form-text">
                  Use negative values for outbound movements if type is <code>out</code>.
                </div>
              </div>
              <div className="col-md-6 mb-3">
                <label className="form-label">
                  Movement Type <span className="text-danger">*</span>
                </label>
                <select
                  className="form-select"
                  required
                  value={movementType}
                  onChange={(e) => setMovementType(e.target.value)}
                >
                  {movementTypes.map((t) => (
                    <option key={t} value={t}>
                      {t.charAt(0).toUpperCase() + t.slice(1)}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="mb-3">
              <label className="form-label">Reason</label>
              <input
                type="text"
                maxLength={120}
                className="form-control"
                placeholder="Short reason (max 120 chars)"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
              />
            </div>

            <div className="mb-3">
              <label className="form-label">Note</label>
              <textarea
                className="form-control"
                rows={3}
                placeholder="Any additional details about this movement..."
                value={note}
                onChange={(e) => setNote(e.target.value)}
              />
            </div>

            <div className="row">
              <div className="col-md-6 mb-3">
                <label className="form-label">Semester</label>
                <select
                  className="form-select"
                  value={semester}
                  onChange={(e) => setSemester(e.target.value)}
                >
                  <option value="">-- None --</option>
                  {semesters.map((sem) => (
                    <option key={sem} value={sem}>
                      {sem}
                    </option>
                  ))}
                </select>
              </div>
              <div className="col-md-6 mb-3">
                <label className="form-label">School Year</label>
                <input
                  type="text"
                  className="form-control"
                  placeholder="e.g., 2025-2026"
                  value={schoolYear}
                  onChange={(e) => setSchoolYear(e.target.value)}
                />
              </div>
            </div>

            <div className="row">
              <div className="col-md-4 mb-3">
                <label className="form-label">Teacher (optional)</label>
                <select
                  className="form-select"
                  value={teacherId}
                  onChange={(e) => setTeacherId(e.target.value)}
                >
                  <option value="">-- None --</option>
                  {teachers.map((t) => (
                    <option key={String(t.id)} value={String(t.id)}>
                      {String(t.fullname ?? t.id)} ({String(t.role ?? '')})
                    </option>
                  ))}
                </select>
              </div>
              <div className="col-md-4 mb-3">
                <label className="form-label">Student (optional)</label>
                <select
                  className="form-select"
                  value={studentId}
                  onChange={(e) => setStudentId(e.target.value)}
                >
                  <option value="">-- None --</option>
                  {students.map((s) => (
                    <option key={String(s.id)} value={String(s.id)}>
                      {String(s.fullname ?? s.id)}
                    </option>
                  ))}
                </select>
              </div>
              <div className="col-md-4 mb-3">
                <label className="form-label">Class Section (optional)</label>
                <select
                  className="form-select"
                  value={classSectionId}
                  onChange={(e) => setClassSectionId(e.target.value)}
                >
                  <option value="">-- None --</option>
                  {classSections.map((cs) => (
                    <option
                      key={String(cs.class_section_id)}
                      value={String(cs.class_section_id)}
                    >
                      {String(cs.class_section_name ?? cs.class_section_id)}
                    </option>
                  ))}
                </select>
                <div className="form-text">Uses the class_section_id code.</div>
              </div>
            </div>

            {!isCreate ? (
              <>
                <hr />
                <div className="row g-3">
                  <div className="col-md-4">
                    <label className="form-label">Performed By</label>
                    <input
                      type="text"
                      className="form-control"
                      value={String(movement.performed_by_name ?? movement.performed_by ?? '—')}
                      disabled
                    />
                  </div>
                  <div className="col-md-4">
                    <label className="form-label">Created At</label>
                    <input
                      type="text"
                      className="form-control"
                      value={String(movement.created_at ?? '—')}
                      disabled
                    />
                  </div>
                  <div className="col-md-4">
                    <label className="form-label">Last Updated</label>
                    <input
                      type="text"
                      className="form-control"
                      value={String(movement.updated_at ?? '—')}
                      disabled
                    />
                  </div>
                </div>
              </>
            ) : null}
          </div>

          <div className="card-footer d-flex gap-2">
            <button type="submit" className="btn btn-primary" disabled={saving}>
              {saving ? 'Saving…' : isCreate ? 'Create Movement' : 'Save Changes'}
            </button>
            <Link className="btn btn-secondary" to="/app/administrator/inventory/movements">
              Cancel
            </Link>
          </div>
        </form>
      ) : null}
    </div>
  )
}
