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

/** ---------- Zeit-Utils: Postgres-String -> RFC3339 ---------- */
function normalizePgTimestamp(s) {
  if (!s || typeof s !== "string") return s;
  let t = s.replace(" ", "T");
  // Mikrosekunden (6 Stellen) -> Millisekunden (3 Stellen)
  t = t.replace(/(\.\d{3})\d+([Z+-])/, "$1$2");
  // Offset +HH / -HH -> +HH:00 / -HH:00
  t = t.replace(/([+-]\d{2})$/, "$1:00");
  return t;
}
function parseTs(s) {
  const iso = normalizePgTimestamp(s);
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? null : d;
}
function formatTsBerlin(s) {
  const d = parseTs(s);
  if (!d) return "—";
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "short",
    timeStyle: "medium",
    timeZone: "Europe/Berlin",
  }).format(d);
}
/** ------------------------------------------------------------- */

export default function BookingsPage() {
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);
  const [productMap, setProductMap] = useState(() => new Map()); // id -> name

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        setLoading(true);
        // Buchungen + Produkte parallel laden (Products nur für Name-Lookup)
        const [bData, pData] = await Promise.all([
          getMyBookings(),
          getProducts().catch(() => []),
        ]);
        if (!alive) return;

        const items = Array.isArray(bData) ? bData : (bData.items || []);
        items.sort((a, b) => {
          const ta = parseTs(a.created_at ?? a.timestamp)?.getTime() ?? 0;
          const tb = parseTs(b.created_at ?? b.timestamp)?.getTime() ?? 0;
          return tb - ta;
        });
        setRows(items);

        const map = new Map();
        if (Array.isArray(pData)) {
          for (const p of pData) {
            if (p && typeof p.id !== "undefined") map.set(p.id, p.name || String(p.id));
          }
        }
        setProductMap(map);
      } catch (e) {
        if (alive) setErr(e);
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <div className="text-white">Lade Buchungen…</div>;
  if (err) return <div className="text-white/70 text-sm">Keine Buchungen verfügbar (Endpoint fehlt oder keine Daten).</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">Meine Buchungen</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">Zeit</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">Gesamt (€)</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => {
              const name =
                r.product?.name ??
                r.product_name ??
                (typeof r.product_id !== "undefined"
                  ? productMap.get(r.product_id) ?? String(r.product_id)
                  : "—");

              return (
                <tr key={r.id ?? r.booking_id} className="border-t border-white/10">
                  <td className="py-2 pr-4 font-mono">
                    {formatTsBerlin(r.created_at ?? r.timestamp)}
                  </td>
                  <td className="py-2 pr-4">{name}</td>
                  <td className="py-2 pr-4 font-mono">
                    {r.amount ?? r.quantity ?? 1}
                  </td>
                  <td className="py-2 pr-4 font-mono">
                    {r.total_cents != null ? (r.total_cents / 100).toFixed(2) : "—"}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
