"use client";

import { useEffect, useState } from "react";
import { DataTable } from "@/components/data-table";
import { getInventory, InventoryRow } from "@/lib/api";

export default function InventoryPage() {
  const [data, setData] = useState<InventoryRow[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    setError(null);
    getInventory()
      .then((rows) => {
        setData(rows);
      })
      .catch((err: unknown) => {
        setError(err instanceof Error ? err.message : "Failed to load inventory.");
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  return (
    <>
      <section className="hero">
        <h2>Inventory by warehouse, item, and batch.</h2>
        <p>
          The table design below mirrors the API contract for current balances and threshold progress.
        </p>
      </section>

      <section className="section">
        <div className="section-header">
          <div>
            <h3>Inventory balances</h3>
            <p>Warehouse-aware, batch-aware, and expiry-ready.</p>
          </div>
          <div className="filters">
            <span className="filter-pill">Warehouse</span>
            <span className="filter-pill">Item</span>
            <span className="filter-pill">Batch</span>
            <span className="filter-pill">Expiry Range</span>
          </div>
        </div>

        {loading && <p>Loading inventory…</p>}

        {!loading && error && (
          <p className="error">{error}</p>
        )}

        {!loading && !error && data && (
          <DataTable
            rows={data as unknown as Record<string, string | number | null | undefined>[]}
            columns={[
              { key: "warehouse", label: "Warehouse" },
              { key: "itemCode", label: "Item Code" },
              { key: "itemName", label: "Item Name" },
              { key: "batchNumber", label: "Batch Number" },
              { key: "expiryDate", label: "Expiry Date" },
              { key: "inboundMt", label: "Inbound MT" },
              { key: "outboundMt", label: "Outbound MT" },
              { key: "availableMt", label: "Available MT" },
            ]}
          />
        )}
      </section>
    </>
  );
}
