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

export default async function ClientTicketsPage() {
  const session = (await getSession())!;
  const db = await getDb();
  const tickets = db.tickets.filter((t) => t.userId === session.uid);
  const serviceNames = db.clientServices.filter((s) => s.userId === session.uid).map((s) => s.name);

  return (
    <>
      <PageTitle
        title="Support tickets"
        sub="15-minute response on critical incidents, one business day otherwise."
        action={<NewTicketForm services={serviceNames} />}
      />
      <Card>
        {tickets.length === 0 ? (
          <Empty text="No tickets yet — open one and our NOC picks it up." />
        ) : (
          <TableShell head={["Subject", "Priority", "Status", "Updated", ""]}>
            {tickets.map((t) => (
              <tr key={t.id} className="border-b border-white/5 last:border-0">
                <td className="px-5 py-3.5">
                  <Link href={`/client/tickets/${t.id}`} className="font-medium text-thi hover:text-ice">
                    {t.subject}
                  </Link>
                  {t.service ? <p className="mt-0.5 text-[0.78rem] text-tlo">{t.service}</p> : null}
                </td>
                <td className="px-5 py-3.5">
                  <Badge value={t.priority} />
                </td>
                <td className="px-5 py-3.5">
                  <Badge value={t.status} />
                </td>
                <td className="px-5 py-3.5 text-tmid tnum">{fmtDate(t.updatedAt)}</td>
                <td className="px-5 py-3.5 text-right">
                  <Link href={`/client/tickets/${t.id}`} className="text-[0.85rem] text-ice hover:underline">
                    Open →
                  </Link>
                </td>
              </tr>
            ))}
          </TableShell>
        )}
      </Card>
    </>
  );
}
