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

/**
 * CI `inventory/edit/:id` — resolves item type and redirects to the typed edit route.
 */
export function InventoryEditEntryPage() {
  const { itemId } = useParams()
  const navigate = useNavigate()
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!itemId) return
    let c = false
    fetchInventoryItem(itemId)
      .then((data) => {
        if (c) return
        const item = (data && typeof data === 'object' ? (data as { item?: unknown }).item : null) ?? data
        const rec = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>
        const t = String(rec.type ?? '')
        const map: Record<string, string> = {
          book: 'book',
          classroom: 'classroom',
          kitchen: 'kitchen',
          office: 'office',
        }
        const seg = map[t]
        if (seg) {
          navigate(`/app/administrator/inventory/${seg}/${itemId}/edit`, { replace: true })
        } else {
          setError('Unknown inventory item type.')
        }
      })
      .catch((e: unknown) => {
        if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load item.')
      })
    return () => {
      c = true
    }
  }, [itemId, navigate])

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

  return (
    <div className="p-3">
      {error ? <div className="alert alert-danger">{error}</div> : <p className="text-muted mb-0">Redirecting…</p>}
    </div>
  )
}
