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

export const metadata: Metadata = {
  title: "My Tickets",
};

type Props = {
  searchParams: Promise<{ status?: string; page?: string }>;
};

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",
};

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

  const { status, page } = await searchParams;
  const currentPage = Math.max(1, parseInt(page || "1", 10));
  const perPage = 20;

  const where: Record<string, unknown> = {
    user_id: parseInt(session.user.id),
  };
  if (status && status !== "all") {
    where.status = status;
  }

  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);

  return (
    <div className="max-w-4xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">My Tickets</h1>
          <p className="text-text-muted text-sm mt-1">{total} ticket{total !== 1 ? "s" : ""}</p>
        </div>
        <Link
          href="/support"
          className="bg-primary hover:bg-primary/90 text-white font-medium rounded-lg px-4 py-2 text-sm transition-colors"
        >
          New Ticket
        </Link>
      </div>

      {/* Status filter */}
      <div className="flex gap-2 mb-6 flex-wrap">
        {["all", "open", "in_progress", "resolved", "closed"].map((s) => (
          <Link
            key={s}
            href={`/support/tickets${s === "all" ? "" : `?status=${s}`}`}
            className={`px-3 py-1.5 rounded-lg text-sm 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>

      {tickets.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center">
          <p className="text-text-muted">No tickets found.</p>
          <Link href="/support" className="text-primary text-sm hover:underline mt-2 inline-block">
            Open a new ticket
          </Link>
        </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">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={`/support/tickets/${ticket.id}`}
                        className="font-medium hover:text-primary transition-colors"
                      >
                        {ticket.subject}
                      </Link>
                    </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",
                        year: "numeric",
                      })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 p-4 border-t border-surface-light">
              {currentPage > 1 && (
                <Link
                  href={`/support/tickets?${status ? `status=${status}&` : ""}page=${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={`/support/tickets?${status ? `status=${status}&` : ""}page=${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>
  );
}
