import { notFound, redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { replyAsCustomer } from "@/lib/actions/support";

const STATUS_LABEL: Record<string, string> = {
  open: "Open",
  in_progress: "In progress",
  resolved: "Resolved",
  closed: "Closed",
};

export default async function TicketThreadPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ email?: string; error?: string }>;
}) {
  const { id } = await params;
  const { email, error } = await searchParams;

  const ticket = await prisma.supportTicket.findUnique({
    where: { id },
    include: { messages: { orderBy: { createdAt: "asc" } } },
  });
  if (!ticket) notFound();

  const sessionCustomerId = await getCurrentCustomerId();
  const owns = (sessionCustomerId && ticket.customerId === sessionCustomerId) || (email && email.trim().toLowerCase() === ticket.email.toLowerCase());
  if (!owns) redirect("/track-order");

  return (
    <div className="mx-auto max-w-2xl px-4 py-14 sm:px-6">
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">{ticket.subject}</h1>
      <p className="mt-1 text-sm text-stone-500">
        Ticket opened {formatDate(ticket.createdAt)} ·{" "}
        <span className={ticket.status === "resolved" || ticket.status === "closed" ? "text-emerald-700" : "text-amber-700"}>
          {STATUS_LABEL[ticket.status]}
        </span>
      </p>

      {error && <p className="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="mt-6 space-y-3">
        {ticket.messages.map((m) => (
          <div key={m.id} className={`rounded-lg border p-3 text-sm ${m.senderType === "staff" ? "border-rose-100 bg-rose-50/50" : "border-stone-200 bg-white"}`}>
            <p className="text-xs font-medium text-stone-500">{m.senderType === "staff" ? "Iniyaval Return Gifts" : ticket.name}</p>
            <p className="mt-1 whitespace-pre-line text-stone-700">{m.body}</p>
            <p className="mt-1 text-xs text-stone-400">{formatDate(m.createdAt)}</p>
          </div>
        ))}
      </div>

      {ticket.status !== "closed" && (
        <form action={replyAsCustomer.bind(null, ticket.id, email ?? null)} className="mt-6 space-y-2">
          <textarea name="body" required maxLength={5000} rows={3} placeholder="Add a reply" className="block w-full rounded-md border border-stone-300 px-3 py-2 text-sm" />
          <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
            Send reply
          </button>
        </form>
      )}
    </div>
  );
}
