"use client";
import { useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import TicketThread from "@/components/TicketThread";

const STATUS_COLORS: Record<string, string> = {
  open: "bg-amber-900/60 text-amber-400",
  in_progress: "bg-blue-900/60 text-blue-400",
  resolved: "bg-green-900/60 text-green-400",
  closed: "bg-neutral-800 text-neutral-400",
};
const STATUS_LABELS: Record<string, string> = {
  open: "Open",
  in_progress: "In Progress",
  resolved: "Resolved",
  closed: "Closed",
};

export default function SupportTicketPage() {
  const params = useParams<{ id: string }>();
  const [ticket, setTicket] = useState<any>(null);
  const [closing, setClosing] = useState(false);

  async function closeTicket() {
    if (!confirm("Close this ticket? You can still follow up later if needed — that reopens it automatically.")) return;
    setClosing(true);
    const res = await fetch(`/api/tickets/${params.id}/close`, { method: "POST" });
    setClosing(false);
    if (res.ok) setTicket((t: any) => ({ ...t, status: "closed" }));
  }

  return (
    <div className="max-w-2xl mx-auto">
      <Link href="/support" className="text-red-500 text-sm mb-4 inline-block">← Back to Support</Link>
      <div className="card p-5">
        <div className="flex items-center justify-between mb-5 pb-4 border-b border-neutral-800">
          <h1 className="text-lg font-bold">{ticket?.subject || "Loading..."}</h1>
          <div className="flex items-center gap-2 shrink-0">
            {ticket && (
              <span className={`text-xs font-medium px-2.5 py-1 rounded-full ${STATUS_COLORS[ticket.status]}`}>
                {STATUS_LABELS[ticket.status]}
              </span>
            )}
            {ticket && !["closed"].includes(ticket.status) && (
              <button onClick={closeTicket} disabled={closing} className="text-xs text-neutral-500 hover:text-white underline">
                {closing ? "Closing..." : "Close ticket"}
              </button>
            )}
          </div>
        </div>
        <TicketThread ticketId={params.id} onTicketLoaded={setTicket} />
      </div>
    </div>
  );
}
