import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchReorderSuggestions } from '../../api/inventory'
import { INVENTORY_BOOK_BASE } from './inventoryPaths'

/**
 * Reorder Suggestions — calculated suggested order quantities for low-stock items.
 * Backend: GET /api/v1/inventory/reorder-suggestions
 */
export function InventoryReorderSuggestionsPage() {
  const [suggestions, setSuggestions] = useState<Record<string, unknown>[]>([])
  const [count, setCount] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(() => {
    setLoading(true)
    fetchReorderSuggestions()
      .then((res) => {
        if (res && typeof res === 'object') {
          const o = res as Record<string, unknown>
          const arr = Array.isArray(o.suggestions) ? (o.suggestions as Record<string, unknown>[]) : []
          setSuggestions(arr)
          setCount(Number(o.count ?? arr.length))
        }
        setError(null)
      })
      .catch((e: unknown) => {
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load reorder suggestions.')
      })
      .finally(() => setLoading(false))
  }, [])

  useEffect(() => {
    load()
  }, [load])

  return (
    <div className="container-fluid px-0 mt-3">
      <div className="d-flex justify-content-between align-items-center mb-3 px-3 flex-wrap gap-2">
        <h3 className="mb-0">Reorder Suggestions ({count})</h3>
        <div className="d-flex gap-2">
          <Link className="btn btn-outline-warning btn-sm" to="/app/administrator/inventory/low-stock">
            Low Stock
          </Link>
          <Link className="btn btn-outline-secondary" to={INVENTORY_BOOK_BASE}>
            Back to Items
          </Link>
        </div>
      </div>

      {error ? <div className="alert alert-danger mx-3">{error}</div> : null}

      {loading ? (
        <p className="text-muted px-3">Loading…</p>
      ) : suggestions.length === 0 ? (
        <div className="alert alert-success mx-3">
          <strong>All stocked up!</strong> No reorder suggestions at this time.
        </div>
      ) : (
        <div className="card mx-3">
          <div className="card-body table-responsive">
            <table className="table table-striped align-middle" id="reorderSuggestionsTable">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Category</th>
                  <th className="text-end">Current Qty</th>
                  <th className="text-end">Reorder Point</th>
                  <th className="text-end">Suggested Order</th>
                  <th>Preferred Supplier</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {suggestions.map((s) => {
                  const supplier = s.preferred_supplier as Record<string, unknown> | null
                  return (
                    <tr key={String(s.id)}>
                      <td>{String(s.name ?? '')}</td>
                      <td>{String(s.category ?? '—')}</td>
                      <td className="text-end text-danger fw-semibold">
                        {Number(s.current_quantity ?? 0).toLocaleString()}
                      </td>
                      <td className="text-end">{Number(s.reorder_point ?? 0).toLocaleString()}</td>
                      <td className="text-end fw-semibold">
                        {Number(s.suggested_order_qty ?? 0).toLocaleString()}
                      </td>
                      <td>{supplier ? String(supplier.name ?? '') : '—'}</td>
                      <td>
                        <Link
                          className="btn btn-sm btn-warning"
                          to={`/app/administrator/inventory/items/${String(s.id)}/adjust`}
                        >
                          Adjust Stock
                        </Link>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
