import { type FormEvent, useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchInventoryItem, postClassroomAudit } from '../../api/inventory'

/** CI `inventory/classroom/audit_form.php` */
export function InventoryClassroomAuditPage() {
  const { itemId } = useParams()
  const [name, setName] = useState('')
  const [qty, setQty] = useState(0)
  const [needsRepair, setNeedsRepair] = useState(0)
  const [needReplace, setNeedReplace] = useState(0)
  const [cannotFind, setCannotFind] = useState(0)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!itemId) return
    let c = false
    setLoading(true)
    fetchInventoryItem(itemId)
      .then((data) => {
        if (c) return
        const item = (data?.item ?? data) as Record<string, unknown>
        setName(String(item.name ?? ''))
        setQty(Number(item.quantity ?? 0))
        setNeedsRepair(Number(item.needs_repair_qty ?? 0))
        setNeedReplace(Number(item.need_replace_qty ?? 0))
        setCannotFind(Number(item.cannot_find_qty ?? 0))
        setError(null)
      })
      .catch((e: unknown) => {
        if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load item.')
      })
      .finally(() => {
        if (!c) setLoading(false)
      })
    return () => {
      c = true
    }
  }, [itemId])

  const derivedGood = Math.max(0, qty - needsRepair)

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    try {
      await postClassroomAudit(itemId ?? '', {
        needs_repair_qty: needsRepair,
        need_replace_qty: needReplace,
        cannot_find_qty: cannotFind,
      })
      window.location.href = '/app/administrator/inventory/classroom'
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  if (!itemId) {
    return (
      <div className="container my-4">
        <div className="alert alert-warning">Missing item id.</div>
      </div>
    )
  }

  return (
    <div className="container my-4">
      <h3 className="mb-3">Audit — {name || '…'}</h3>
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading ? (
        <>
          <div className="alert alert-info">
            <strong>Current On Hand:</strong> {qty} pcs
          </div>

          <form onSubmit={(ev) => void onSubmit(ev)}>
            <div className="row g-3">
              <div className="col-md-3">
                <label className="form-label">Needs Repair</label>
                <input
                  type="number"
                  min={0}
                  className="form-control"
                  value={needsRepair}
                  onChange={(e) => setNeedsRepair(Number(e.target.value))}
                />
              </div>
              <div className="col-md-3">
                <label className="form-label">Total Loss (Need Replace)</label>
                <input
                  type="number"
                  min={0}
                  className="form-control"
                  value={needReplace}
                  onChange={(e) => setNeedReplace(Number(e.target.value))}
                />
              </div>
              <div className="col-md-3">
                <label className="form-label">Cannot Find</label>
                <input
                  type="number"
                  min={0}
                  className="form-control"
                  value={cannotFind}
                  onChange={(e) => setCannotFind(Number(e.target.value))}
                />
              </div>
              <div className="col-md-3">
                <label className="form-label">Derived Good (read-only)</label>
                <input type="number" className="form-control" value={derivedGood} readOnly />
                <div className="form-text">Good = On Hand − Needs Repair</div>
              </div>
            </div>

            <div className="mt-3 d-flex gap-2">
              <button type="submit" className="btn btn-primary" disabled={saving}>
                {saving ? 'Saving…' : 'Save Audit'}
              </button>
              <Link className="btn btn-outline-secondary" to="/app/administrator/inventory/classroom">
                Cancel
              </Link>
            </div>
          </form>
        </>
      ) : null}
    </div>
  )
}
