import React, { useEffect, useState } from "react";
import { getDeliveries } from "../../api";

export default function DeliveriesPage() {
  const [rows, setRows] = useState([]);
  const [err, setErr] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const data = await getDeliveries();
        if (!alive) return;
        setRows(Array.isArray(data) ? data : []);
      } catch (e) {
        if (alive) setErr(e);
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <div className="text-white">Lade Lieferungen…</div>;
  if (err) return <div className="text-red-300">Fehler: {String(err.message || err)}</div>;

  return (
    <div className="rounded-2xl bg-white/5 border border-cyan-400/20 p-5">
      <h2 className="text-white/90 font-semibold mb-3">Lieferungen</h2>
      <div className="overflow-x-auto">
        <table className="min-w-full text-sm text-white/80">
          <thead className="text-white/60">
            <tr>
              <th className="text-left py-2 pr-4">ID</th>
              <th className="text-left py-2 pr-4">Produkt</th>
              <th className="text-left py-2 pr-4">Menge</th>
              <th className="text-left py-2 pr-4">Preis (€)</th>
              <th className="text-left py-2 pr-4">Notiz</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((d) => (
              <tr key={d.id} className="border-t border-white/10">
                <td className="py-2 pr-4 font-mono">{d.id}</td>
                <td className="py-2 pr-4">{d.product?.name ?? d.product_id}</td>
                <td className="py-2 pr-4 font-mono">{d.amount}</td>
                <td className="py-2 pr-4 font-mono">{((d.price_cents ?? 0)/100).toFixed(2)}</td>
                <td className="py-2 pr-4">{d.note ?? "–"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
