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

export default async function AdminCitiesPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const params = await searchParams;
  const page = Math.max(1, parseInt(String(params.page ?? "1")));
  const perPage = 50;
  const search = String(params.search ?? "");

  const where = search
    ? { name: { contains: search, mode: "insensitive" as const } }
    : {};

  const [cities, total] = await Promise.all([
    prisma.city.findMany({
      where,
      orderBy: { name: "asc" },
      skip: (page - 1) * perPage,
      take: perPage,
      include: {
        country: { select: { name: true } },
      },
    }),
    prisma.city.count({ where }),
  ]);

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

  function buildUrl(overrides: Record<string, string>) {
    const p = new URLSearchParams();
    if (search) p.set("search", search);
    p.set("page", String(page));
    Object.entries(overrides).forEach(([k, v]) => p.set(k, v));
    return `/admin/cities?${p.toString()}`;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">City Management</h1>
        <Link
          href="/admin/cities/create"
          className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors text-sm"
        >
          Add City
        </Link>
      </div>

      {/* Search */}
      <div className="bg-surface rounded-lg p-4">
        <form className="flex gap-4 items-end">
          <div className="flex-1 min-w-[200px]">
            <label className="block text-text-muted text-sm mb-1">
              Search
            </label>
            <input
              type="text"
              name="search"
              defaultValue={search}
              placeholder="City name..."
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>
          <button
            type="submit"
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors"
          >
            Search
          </button>
        </form>
      </div>

      <p className="text-text-muted text-sm">
        Showing {(page - 1) * perPage + 1}-
        {Math.min(page * perPage, total)} of {total.toLocaleString()} cities
      </p>

      {/* Table */}
      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-surface-light text-text-muted text-sm">
                <th className="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">Name</th>
                <th className="p-4 font-medium">Slug</th>
                <th className="p-4 font-medium">Country</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {cities.map((city) => (
                <tr
                  key={city.id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {city.id}
                  </td>
                  <td className="p-4 font-medium">{city.name}</td>
                  <td className="p-4 text-text-muted text-sm">{city.slug}</td>
                  <td className="p-4 text-text-muted">
                    {city.country?.name || "-"}
                  </td>
                  <td className="p-4">
                    <Link
                      href={`/admin/cities/edit/${city.slug}`}
                      className="text-primary hover:text-primary-dark text-sm transition-colors"
                    >
                      Edit
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <Link
              href={buildUrl({ page: String(page - 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Previous
            </Link>
          )}
          {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
            let pageNum: number;
            if (totalPages <= 7) {
              pageNum = i + 1;
            } else if (page <= 4) {
              pageNum = i + 1;
            } else if (page >= totalPages - 3) {
              pageNum = totalPages - 6 + i;
            } else {
              pageNum = page - 3 + i;
            }
            return (
              <Link
                key={pageNum}
                href={buildUrl({ page: String(pageNum) })}
                className={`px-3 py-1.5 rounded text-sm transition-colors ${
                  pageNum === page
                    ? "bg-primary text-white"
                    : "bg-surface hover:bg-surface-light text-text-muted"
                }`}
              >
                {pageNum}
              </Link>
            );
          })}
          {page < totalPages && (
            <Link
              href={buildUrl({ page: String(page + 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
