import { auth } from "@/lib/auth";
import { redirect, notFound } from "next/navigation";
import prisma from "@/lib/prisma";
import Link from "next/link";
import type { Metadata } from "next";
import TicketReplyForm from "./TicketReplyForm";

export const metadata: Metadata = {
  title: "Ticket Detail",
};

const STATUS_COLORS: Record<string, string> = {
  open: "bg-blue-500/20 text-blue-400",
  in_progress: "bg-yellow-500/20 text-yellow-400",
  resolved: "bg-green-500/20 text-green-400",
  closed: "bg-gray-500/20 text-gray-400",
};

const PRIORITY_COLORS: Record<string, string> = {
  normal: "bg-surface-light text-text-muted",
  high: "bg-red-500/20 text-red-400",
};

type Props = {
  params: Promise<{ id: string }>;
};

export default async function TicketDetailPage({ params }: Props) {
  const session = await auth();
  if (!session?.user?.id) redirect("/login?callbackUrl=/support/tickets");

  const { id } = await params;
  const ticketId = parseInt(id, 10);
  if (isNaN(ticketId)) notFound();

  const ticket = await prisma.ticket.findUnique({
    where: { id: ticketId },
    include: {
      messages: {
        orderBy: { created_at: "asc" },
      },
    },
  });

  if (!ticket) notFound();

  // Only owner can view
  if (ticket.user_id !== parseInt(session.user.id)) {
    notFound();
  }

  const isResolved = ticket.status === "resolved" || ticket.status === "closed";

  return (
    <div className="max-w-3xl mx-auto">
      <div className="mb-6">
        <Link href="/support/tickets" className="text-text-muted hover:text-text text-sm transition-colors">
          &larr; Back to My Tickets
        </Link>
      </div>

      {/* Header */}
      <div className="bg-surface rounded-xl border border-surface-light p-6 mb-6">
        <div className="flex flex-wrap items-start gap-3 mb-3">
          <span className={`px-2 py-0.5 rounded text-xs font-medium ${STATUS_COLORS[ticket.status] || ""}`}>
            {ticket.status.replace("_", " ")}
          </span>
          <span className={`px-2 py-0.5 rounded text-xs font-medium ${PRIORITY_COLORS[ticket.priority] || ""}`}>
            {ticket.priority}
          </span>
          <span className="px-2 py-0.5 rounded text-xs font-medium bg-surface-light text-text-muted capitalize">
            {ticket.category}
          </span>
        </div>
        <h1 className="text-xl font-bold">{ticket.subject}</h1>
        <p className="text-text-muted text-xs mt-2">
          Ticket #{ticket.id} &middot; Created{" "}
          {new Date(ticket.created_at).toLocaleDateString(undefined, {
            day: "numeric",
            month: "short",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
          })}
        </p>
      </div>

      {/* Messages */}
      <div className="space-y-4 mb-8">
        {ticket.messages.map((msg) => (
          <div
            key={msg.id}
            className={`rounded-xl p-4 ${
              msg.is_ai
                ? "bg-purple-500/10 border border-purple-500/20"
                : msg.is_admin
                ? "bg-blue-500/10 border border-blue-500/20"
                : "bg-surface border border-surface-light"
            }`}
          >
            <div className="flex items-center gap-2 mb-2">
              <span className="text-xs font-medium">
                {msg.is_ai ? "AI Assistant" : msg.is_admin ? "Support Team" : "You"}
              </span>
              <span className="text-text-muted text-xs">
                {new Date(msg.created_at).toLocaleDateString(undefined, {
                  day: "numeric",
                  month: "short",
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </span>
            </div>
            <div className="text-sm whitespace-pre-wrap leading-relaxed">{msg.body}</div>
          </div>
        ))}
      </div>

      {/* Reply form */}
      {!isResolved ? (
        <div className="bg-surface rounded-xl border border-surface-light p-6">
          <TicketReplyForm ticketId={ticket.id} />
        </div>
      ) : (
        <div className="bg-surface rounded-xl border border-surface-light p-6 text-center text-text-muted text-sm">
          This ticket has been {ticket.status}. If you need further help,{" "}
          <Link href="/support" className="text-primary hover:underline">
            open a new ticket
          </Link>
          .
        </div>
      )}
    </div>
  );
}
