import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { replyAsStaff, updateTicketStatus } from "@/lib/actions/support";

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

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

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

  return (
    <div>
      <Link href="/iv-manage-84x2/support" className="text-sm text-stone-500 hover:text-rose-700">
        ← All tickets
      </Link>
      <div className="mt-2 flex items-center justify-between">
        <div>
          <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.name} · {ticket.email} · opened {formatDate(ticket.createdAt)}
          </p>
        </div>
        <form action={updateTicketStatus.bind(null, ticket.id)} className="flex items-center gap-2">
          <select name="status" defaultValue={ticket.status} className="rounded-md border border-stone-300 px-2 py-1.5 text-sm">
            {STATUSES.map((s) => (
              <option key={s} value={s}>
                {STATUS_LABEL[s]}
              </option>
            ))}
          </select>
          <button type="submit" className="rounded-md border border-stone-300 px-3 py-1.5 text-sm font-medium text-stone-600 hover:bg-stone-50">
            Update
          </button>
        </form>
      </div>

      {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 max-w-2xl 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" ? "You (staff)" : 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>

      <form action={replyAsStaff.bind(null, ticket.id)} className="mt-6 max-w-2xl space-y-2">
        <textarea name="body" required maxLength={5000} rows={4} placeholder="Reply — this emails the customer" 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>
  );
}
