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

/** CI `inventory/adjust_form.php` */
export function InventoryAdjustPage() {
  const { itemId } = useParams()
  const [searchParams] = useSearchParams()
  const [name, setName] = useState('')
  const [itemType, setItemType] = useState('')
  const [mode, setMode] = useState('in')
  const [quantity, setQuantity] = useState('1')
  const [reason, setReason] = useState('')
  const [note, setNote] = useState('')
  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 ?? ''))
        setItemType(String(item.type ?? ''))
        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 summaryHref =
    itemType && itemType !== ''
      ? `/app/administrator/inventory/summary?${searchParams.toString()}`
      : '/app/administrator/inventory/summary'

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    try {
      await postInventoryAdjust(itemId ?? '', {
        mode,
        quantity: Number(quantity),
        reason: reason || undefined,
        note: note || undefined,
      })
      window.location.href = summaryHref
    } 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">Adjust Stock — {name || '…'}</h3>
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading ? (
        <form onSubmit={(ev) => void onSubmit(ev)}>
          <div className="row g-3">
            <div className="col-md-3">
              <label className="form-label">Mode</label>
              <select
                className="form-select"
                required
                value={mode}
                onChange={(e) => setMode(e.target.value)}
              >
                <option value="in">Add to Stock</option>
                <option value="out">Deduct from Stock</option>
                <option value="adjust">Adjust (signed)</option>
              </select>
            </div>
            <div className="col-md-3">
              <label className="form-label">Quantity</label>
              <input
                type="number"
                min={1}
                className="form-control"
                required
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
              />
            </div>
            <div className="col-md-6">
              <label className="form-label">Reason</label>
              <input
                className="form-control"
                placeholder="Purchase, Donation, Correction, etc."
                value={reason}
                onChange={(e) => setReason(e.target.value)}
              />
            </div>
            <div className="col-12">
              <label className="form-label">Note (optional)</label>
              <textarea className="form-control" rows={3} value={note} onChange={(e) => setNote(e.target.value)} />
            </div>
          </div>

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