"use client";

import type { Reservation } from "@prisma/client";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";

function fmtDate(d: string) {
  try {
    return new Date(d).toLocaleString();
  } catch {
    return d;
  }
}

export function AdminReservationsTable() {
  const t = useTranslations("admin");
  const [rows, setRows] = useState<Reservation[]>([]);
  const [loading, setLoading] = useState(true);

  async function refresh() {
    const res = await fetch("/api/admin/reservations");
    if (res.ok) setRows(await res.json());
  }

  useEffect(() => {
    (async () => {
      await refresh();
      setLoading(false);
    })();
  }, []);

  async function setStatus(id: string, status: string) {
    const res = await fetch("/api/admin/reservations", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status }),
    });
    if (res.ok) await refresh();
  }

  if (loading) return <p className="text-muted">…</p>;

  if (rows.length === 0) {
    return <p className="text-muted">{t("noReservations")}</p>;
  }

  return (
    <div className="overflow-x-auto rounded-xl border border-border">
      <table className="w-full min-w-[640px] text-left text-sm">
        <thead className="border-b border-border bg-card/50 text-muted">
          <tr>
            <th className="p-3 font-medium">{t("status")}</th>
            <th className="p-3 font-medium">{t("guest")}</th>
            <th className="p-3 font-medium">{t("when")}</th>
            <th className="p-3 font-medium">Email</th>
            <th className="p-3 font-medium">{t("actions")}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.id} className="border-b border-border/80">
              <td className="p-3 capitalize text-gold">{r.status}</td>
              <td className="p-3">
                {r.name}
                <span className="text-muted"> · {r.partySize}</span>
              </td>
              <td className="p-3 text-muted">
                {fmtDate(r.date.toString())} {r.time}
              </td>
              <td className="p-3 text-muted">{r.email}</td>
              <td className="p-3">
                <div className="flex flex-wrap gap-1">
                  {(["pending", "confirmed", "cancelled"] as const).map((s) => (
                    <button
                      key={s}
                      type="button"
                      onClick={() => setStatus(r.id, s)}
                      className={`rounded px-2 py-1 text-xs ${
                        r.status === s
                          ? "bg-gold text-background"
                          : "bg-background text-muted hover:text-gold"
                      }`}
                    >
                      {t(s)}
                    </button>
                  ))}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
