import Link from "next/link";
import { notFound } from "next/navigation";
import { getDb } from "@/lib/db";
import { PageTitle, Card, Badge, fmtDate } from "@/components/panel/ui";
import { TicketReply } from "@/components/panel/TicketForms";

export default async function AdminTicketPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const db = await getDb();
  const ticket = db.tickets.find((t) => t.id === id);
  if (!ticket) notFound();
  const user = db.users.find((u) => u.id === ticket.userId);

  return (
    <>
      <PageTitle
        title={ticket.subject}
        sub={`${user?.company ?? "Unknown client"} · ${ticket.service ?? "General"} · opened ${fmtDate(ticket.createdAt)}`}
        action={
          <div className="flex gap-2">
            <Badge value={ticket.priority} />
            <Badge value={ticket.status} />
          </div>
        }
      />
      <Link href="/admin/tickets" className="mb-5 inline-block text-[0.88rem] text-tlo hover:text-ice">
        ← Ticket queue
      </Link>

      <Card className="p-6">
        <ol className="grid gap-5">
          {ticket.messages.map((m, i) => (
            <li
              key={i}
              className={`max-w-[70ch] rounded-xl border p-5 ${
                m.from === "support"
                  ? "border-azure/25 bg-azure/5"
                  : "border-white/10 bg-white/[0.03]"
              }`}
            >
              <div className="flex items-baseline justify-between gap-4">
                <b className={`text-[0.88rem] font-semibold ${m.from === "support" ? "text-azure-bright" : "text-thi"}`}>
                  {m.author}
                </b>
                <span className="font-[family-name:var(--font-mono)] text-[0.72rem] text-tlo tnum">
                  {fmtDate(m.at)}
                </span>
              </div>
              <p className="mt-2 whitespace-pre-wrap text-[0.93rem] leading-relaxed text-tmid">{m.text}</p>
            </li>
          ))}
        </ol>
        <TicketReply ticketId={ticket.id} canClose />
      </Card>
    </>
  );
}
