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

export default async function ClientTicketPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = (await getSession())!;
  const db = await getDb();
  const ticket = db.tickets.find((t) => t.id === id && t.userId === session.uid);
  if (!ticket) notFound();

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

        {ticket.status !== "closed" ? (
          <TicketReply ticketId={ticket.id} canClose />
        ) : (
          <p className="mt-5 border-t border-white/10 pt-5 text-[0.88rem] text-tlo">
            This ticket is closed. Open a new one if the issue returns — we keep the history.
          </p>
        )}
      </Card>
    </>
  );
}
