import prisma from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import AdminTicketActions from "./AdminTicketActions";

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 AdminTicketDetailPage({ params }: Props) {
  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();

  // Fetch user info
  const user = await prisma.user.findUnique({
    where: { id: ticket.user_id },
    select: { id: true, username: true, email: true },
  });

  return (
    <div className="max-w-4xl">
      <div className="mb-6">
        <Link href="/admin/tickets" className="text-text-muted hover:text-text text-sm transition-colors">
          &larr; Back to 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>
          {ticket.form_type && (
            <span className="px-2 py-0.5 rounded text-xs font-medium bg-surface-light text-text-muted">
              {ticket.form_type}
            </span>
          )}
        </div>
        <h1 className="text-xl font-bold">{ticket.subject}</h1>
        <div className="flex flex-wrap gap-4 mt-3 text-xs text-text-muted">
          <span>Ticket #{ticket.id}</span>
          <span>
            User: {user?.username || user?.email || `#${ticket.user_id}`}
          </span>
          {ticket.assigned_to && <span>Assigned to: #{ticket.assigned_to}</span>}
          <span>
            Created:{" "}
            {new Date(ticket.created_at).toLocaleDateString(undefined, {
              day: "numeric",
              month: "short",
              year: "numeric",
              hour: "2-digit",
              minute: "2-digit",
            })}
          </span>
        </div>
      </div>

      {/* AI Summary */}
      {ticket.ai_summary && (
        <div className="bg-purple-500/10 border border-purple-500/20 rounded-xl p-5 mb-6">
          <h3 className="text-sm font-semibold text-purple-300 mb-2">AI Summary</h3>
          <div className="text-sm whitespace-pre-wrap leading-relaxed">{ticket.ai_summary}</div>
        </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
                  ? "Admin"
                  : user?.username || `User #${msg.user_id}`}
              </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>

      {/* Admin Actions */}
      <AdminTicketActions
        ticketId={ticket.id}
        currentStatus={ticket.status}
        currentPriority={ticket.priority}
        currentAssignedTo={ticket.assigned_to}
      />
    </div>
  );
}
