import { useEffect, useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { catalog, inventory } from '@/api/client'
import type { Item, Location } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { ErrorBox } from '@/components/ErrorBox'

export function AdjustStockPage() {
  const navigate = useNavigate()
  const [items, setItems] = useState<Item[]>([])
  const [locations, setLocations] = useState<Location[]>([])
  const [itemCode, setItemCode] = useState('')
  const [locationId, setLocationId] = useState('')
  const [quantity, setQuantity] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  const [result, setResult] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([catalog.listItems(), inventory.listLocations()]).then(([i, l]) => {
      setItems(i)
      setLocations(l.filter((x) => x.active))
      if (i.length > 0) setItemCode(i[0].code)
      if (l.length > 0) setLocationId(l[0].id)
    })
  }, [])

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setResult(null)
    setSubmitting(true)
    try {
      const bal = await inventory.adjustBalance({
        itemCode,
        locationId,
        quantity: Number(quantity),
      })
      setResult(
        `Balance set: ${bal.itemCode} @ location = ${bal.quantity}`,
      )
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <PageHeader
        title="Adjust Stock"
        subtitle="Set the on-hand quantity for an item at a location. Creates the balance row if it doesn't exist."
        actions={<button className="btn-secondary" onClick={() => navigate('/balances')}>← Balances</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-lg">
        <div>
          <label className="block text-sm font-medium text-slate-700">Item</label>
          <select required value={itemCode} onChange={(e) => setItemCode(e.target.value)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm">
            {items.map((i) => <option key={i.id} value={i.code}>{i.code} — {i.name}</option>)}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700">Location</label>
          <select required value={locationId} onChange={(e) => setLocationId(e.target.value)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm">
            {locations.map((l) => <option key={l.id} value={l.id}>{l.code} — {l.name}</option>)}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700">Quantity (absolute, not delta)</label>
          <input type="number" required min="0" step="1" value={quantity}
            onChange={(e) => setQuantity(e.target.value)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-right" />
        </div>
        {error && <ErrorBox error={error} />}
        {result && (
          <div className="rounded-md border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm text-emerald-800">
            {result}
          </div>
        )}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? 'Adjusting...' : 'Set Balance'}
        </button>
      </form>
    </div>
  )
}
