import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";

const STATUS_STYLE: Record<string, string> = {
  open: "bg-amber-100 text-amber-800",
  in_progress: "bg-sky-100 text-sky-800",
  resolved: "bg-emerald-100 text-emerald-800",
  closed: "bg-stone-200 text-stone-600",
};
const STATUS_LABEL: Record<string, string> = {
  open: "Open",
  in_progress: "In progress",
  resolved: "Resolved",
  closed: "Closed",
};

export default async function AdminSupportPage() {
  const tickets = await prisma.supportTicket.findMany({
    orderBy: [{ status: "asc" }, { createdAt: "desc" }],
    include: { _count: { select: { messages: true } } },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Support</h1>
      <p className="mt-1 text-sm text-stone-500">
        A real inbox for questions from the contact form and customer accounts — not a pull from WhatsApp or email, since those
        aren&apos;t connected here. Keep using WhatsApp/email directly for those conversations.
      </p>

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {tickets.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No tickets yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Subject</th>
                <th className="p-3">From</th>
                <th className="p-3">Messages</th>
                <th className="p-3">Status</th>
                <th className="p-3">Opened</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {tickets.map((t) => (
                <tr key={t.id}>
                  <td className="p-3">
                    <Link href={`/iv-manage-84x2/support/${t.id}`} className="font-medium text-rose-700 hover:underline">
                      {t.subject}
                    </Link>
                  </td>
                  <td className="p-3 text-stone-600">
                    {t.name}
                    <div className="text-xs text-stone-400">{t.email}</div>
                  </td>
                  <td className="p-3 text-stone-500">{t._count.messages}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_STYLE[t.status]}`}>{STATUS_LABEL[t.status]}</span>
                  </td>
                  <td className="p-3 text-stone-500">{formatDate(t.createdAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
