import prisma from "@/lib/prisma";
import Link from "next/link";

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 = {
  searchParams: Promise<{ status?: string; category?: string; priority?: string; q?: string; page?: string }>;
};

export default async function AdminTicketsPage({ searchParams }: Props) {
  const { status, category, priority, q, page } = await searchParams;
  const currentPage = Math.max(1, parseInt(page || "1", 10));
  const perPage = 30;

  const where: Record<string, unknown> = {};

  if (status && status !== "all") where.status = status;
  if (category && category !== "all") where.category = category;
  if (priority && priority !== "all") where.priority = priority;
  if (q && q.trim()) {
    where.OR = [
      { subject: { contains: q, mode: "insensitive" } },
    ];
  }

  const [tickets, total] = await Promise.all([
    prisma.ticket.findMany({
      where,
      orderBy: { updated_at: "desc" },
      skip: (currentPage - 1) * perPage,
      take: perPage,
    }),
    prisma.ticket.count({ where }),
  ]);

  const totalPages = Math.ceil(total / perPage);

  function buildQuery(overrides: Record<string, string>) {
    const p = { status: status || "", category: category || "", priority: priority || "", q: q || "", page: "1", ...overrides };
    const qs = Object.entries(p).filter(([, v]) => v && v !== "all").map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
    return qs ? `?${qs}` : "";
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Support Tickets</h1>
          <p className="text-text-muted text-sm mt-1">{total} ticket{total !== 1 ? "s" : ""}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-4 mb-6">
        {/* Status */}
        <div className="flex gap-1">
          {["all", "open", "in_progress", "resolved", "closed"].map((s) => (
            <Link
              key={s}
              href={`/admin/tickets${buildQuery({ status: s })}`}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                (status || "all") === s
                  ? "bg-primary text-white"
                  : "bg-surface text-text-muted hover:bg-surface-light"
              }`}
            >
              {s.replace("_", " ").replace(/\b\w/g, (c) => c.toUpperCase())}
            </Link>
          ))}
        </div>

        {/* Category */}
        <div className="flex gap-1">
          {["all", "verification", "payment", "account", "safety", "technical", "profile", "agency", "general"].map((c) => (
            <Link
              key={c}
              href={`/admin/tickets${buildQuery({ category: c })}`}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                (category || "all") === c
                  ? "bg-primary text-white"
                  : "bg-surface text-text-muted hover:bg-surface-light"
              }`}
            >
              {c.replace(/\b\w/g, (ch) => ch.toUpperCase())}
            </Link>
          ))}
        </div>

        {/* Search */}
        <form className="flex-1 min-w-[200px]">
          <input type="hidden" name="status" value={status || ""} />
          <input type="hidden" name="category" value={category || ""} />
          <input type="hidden" name="priority" value={priority || ""} />
          <input
            type="search"
            name="q"
            defaultValue={q || ""}
            placeholder="Search tickets..."
            className="w-full bg-surface border border-surface-light rounded-lg px-3 py-1.5 text-sm text-text placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
          />
        </form>
      </div>

      {/* Table */}
      {tickets.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center text-text-muted">
          No tickets found.
        </div>
      ) : (
        <div className="bg-surface rounded-xl border border-surface-light overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-surface-light text-left">
                  <th className="px-4 py-3 font-medium text-text-muted">#</th>
                  <th className="px-4 py-3 font-medium text-text-muted">Subject</th>
                  <th className="px-4 py-3 font-medium text-text-muted">User</th>
                  <th className="px-4 py-3 font-medium text-text-muted">Category</th>
                  <th className="px-4 py-3 font-medium text-text-muted">Status</th>
                  <th className="px-4 py-3 font-medium text-text-muted">Priority</th>
                  <th className="px-4 py-3 font-medium text-text-muted">Updated</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-surface-light">
                {tickets.map((ticket) => (
                  <tr key={ticket.id} className="hover:bg-surface-light/50 transition-colors">
                    <td className="px-4 py-3 text-text-muted">{ticket.id}</td>
                    <td className="px-4 py-3">
                      <Link
                        href={`/admin/tickets/${ticket.id}`}
                        className="font-medium hover:text-primary transition-colors"
                      >
                        {ticket.subject}
                      </Link>
                    </td>
                    <td className="px-4 py-3 text-text-muted">#{ticket.user_id}</td>
                    <td className="px-4 py-3 text-text-muted capitalize">{ticket.category}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${STATUS_COLORS[ticket.status] || ""}`}>
                        {ticket.status.replace("_", " ")}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${PRIORITY_COLORS[ticket.priority] || ""}`}>
                        {ticket.priority}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-text-muted text-xs">
                      {new Date(ticket.updated_at).toLocaleDateString(undefined, {
                        day: "numeric",
                        month: "short",
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 p-4 border-t border-surface-light">
              {currentPage > 1 && (
                <Link
                  href={`/admin/tickets${buildQuery({ page: String(currentPage - 1) })}`}
                  className="px-3 py-1.5 rounded bg-surface-light text-text-muted hover:text-text text-sm transition-colors"
                >
                  Previous
                </Link>
              )}
              <span className="text-text-muted text-sm">
                Page {currentPage} of {totalPages}
              </span>
              {currentPage < totalPages && (
                <Link
                  href={`/admin/tickets${buildQuery({ page: String(currentPage + 1) })}`}
                  className="px-3 py-1.5 rounded bg-surface-light text-text-muted hover:text-text text-sm transition-colors"
                >
                  Next
                </Link>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
