import prisma from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import Link from "next/link";

const SORT_OPTIONS = [
  { value: "newest", label: "Newest registered" },
  { value: "oldest", label: "Oldest registered" },
  { value: "recently_online", label: "Recently online" },
  { value: "username_asc", label: "Username A–Z" },
  { value: "username_desc", label: "Username Z–A" },
  { value: "most_viewed", label: "Most viewed" },
] as const;

type SortOption = (typeof SORT_OPTIONS)[number]["value"];

export default async function AdminUsersPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const page = Math.max(1, parseInt(String(params.page ?? "1")));
  const perPage = 25;
  const search = String(params.search ?? "");
  const typeFilter = String(params.type ?? "");
  const statusFilter = String(params.status ?? "");
  const verificationFilter = String(params.verification ?? "");
  const rawCountryFilter = String(params.country ?? "");
  const countryFilter =
    /^\d+$/.test(rawCountryFilter) && Number(rawCountryFilter) > 0
      ? Number(rawCountryFilter)
      : null;
  const requestedSort = String(params.sort ?? "newest");
  const sort: SortOption = SORT_OPTIONS.some((option) => option.value === requestedSort)
    ? (requestedSort as SortOption)
    : "newest";

  const where: Prisma.UserWhereInput = {
    ...(search
      ? {
          OR: [
            { username: { contains: search } },
            { email: { contains: search } },
            { id_aw: { contains: search } },
          ],
        }
      : {}),
    ...(typeFilter ? { user_type: typeFilter as Prisma.EnumUserTypeFilter["equals"] } : {}),
    ...(statusFilter === "active"
      ? { active: true }
      : statusFilter === "inactive"
        ? { active: false }
        : {}),
    ...(verificationFilter === "verified"
      ? { is_verified: true }
      : verificationFilter === "unverified"
        ? { is_verified: false }
        : {}),
    ...(countryFilter ? { country_id: countryFilter } : {}),
  };

  const orderBy: Prisma.UserOrderByWithRelationInput[] =
    sort === "oldest"
      ? [{ created_at: "asc" }, { id: "asc" }]
      : sort === "recently_online"
        ? [{ lastonline_at: { sort: "desc", nulls: "last" } }, { id: "desc" }]
        : sort === "username_asc"
          ? [{ username: { sort: "asc", nulls: "last" } }, { id: "asc" }]
          : sort === "username_desc"
            ? [{ username: { sort: "desc", nulls: "last" } }, { id: "desc" }]
            : sort === "most_viewed"
              ? [{ hits: "desc" }, { id: "desc" }]
              : [{ created_at: "desc" }, { id: "desc" }];

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

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

  function buildUrl(overrides: Record<string, string>) {
    const p = new URLSearchParams();
    if (search) p.set("search", search);
    if (typeFilter) p.set("type", typeFilter);
    if (statusFilter) p.set("status", statusFilter);
    if (verificationFilter) p.set("verification", verificationFilter);
    if (countryFilter) p.set("country", String(countryFilter));
    if (sort !== "newest") p.set("sort", sort);
    p.set("page", String(page));
    Object.entries(overrides).forEach(([k, v]) => p.set(k, v));
    return `/admin/users?${p.toString()}`;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">User Management</h1>
        <div className="flex gap-2">
          <a
            href="/api/admin/users/export"
            className="bg-surface hover:bg-surface-light text-text-muted px-4 py-2 rounded-lg transition-colors text-sm border border-surface-light"
          >
            Export CSV
          </a>
          <Link
            href="/admin/users/create"
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            Add User
          </Link>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-surface rounded-lg p-4">
        <form className="grid gap-4 sm:grid-cols-2 xl:grid-cols-6">
          <div className="sm:col-span-2 xl:col-span-2">
            <label className="block text-text-muted text-sm mb-1">Search</label>
            <input
              type="text"
              name="search"
              defaultValue={search}
              placeholder="Username, email, or ID..."
              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>
          <div>
            <label className="block text-text-muted text-sm mb-1">Type</label>
            <select
              name="type"
              defaultValue={typeFilter}
              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"
            >
              <option value="">All types</option>
              <option value="escort">Escort</option>
              <option value="user">Member</option>
              <option value="admin">Admin</option>
              <option value="developer">Developer</option>
              <option value="strip_club">Strip Club</option>
              <option value="streamer">Streamer</option>
            </select>
          </div>
          <div>
            <label className="block text-text-muted text-sm mb-1">Status</label>
            <select
              name="status"
              defaultValue={statusFilter}
              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"
            >
              <option value="">All statuses</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
          <div>
            <label className="block text-text-muted text-sm mb-1">Verification</label>
            <select
              name="verification"
              defaultValue={verificationFilter}
              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"
            >
              <option value="">All verification</option>
              <option value="verified">Verified</option>
              <option value="unverified">Unverified</option>
            </select>
          </div>
          <div>
            <label className="block text-text-muted text-sm mb-1">Country</label>
            <select
              name="country"
              defaultValue={countryFilter ? String(countryFilter) : ""}
              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"
            >
              <option value="">All countries</option>
              {countries.map((country) => (
                <option key={country.id} value={country.id}>
                  {country.name} ({country._count.users.toLocaleString()})
                </option>
              ))}
            </select>
          </div>
          <div className="sm:col-span-2 xl:col-span-2">
            <label className="block text-text-muted text-sm mb-1">Sort by</label>
            <select
              name="sort"
              defaultValue={sort}
              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"
            >
              {SORT_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
          <div className="flex items-end gap-2 sm:col-span-2 xl:col-span-4">
            <button
              type="submit"
              className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors"
            >
              Apply filters
            </button>
            {(search ||
              typeFilter ||
              statusFilter ||
              verificationFilter ||
              countryFilter ||
              sort !== "newest") && (
              <Link
                href="/admin/users"
                className="bg-surface-light hover:bg-white/10 text-text-muted px-4 py-2 rounded-lg transition-colors"
              >
                Clear
              </Link>
            )}
          </div>
        </form>
      </div>

      {/* Results info */}
      <p className="text-text-muted text-sm">
        Showing {total === 0 ? 0 : (page - 1) * perPage + 1}-
        {Math.min(page * perPage, total)} of {total.toLocaleString()} users
      </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">Username</th>
                <th className="p-4 font-medium">Email</th>
                <th className="p-4 font-medium">Type</th>
                <th className="p-4 font-medium">Country</th>
                <th className="p-4 font-medium">Status</th>
                <th className="p-4 font-medium">Last Online</th>
                <th className="p-4 font-medium">Registered</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr
                  key={user.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">
                    {user.id_aw}
                  </td>
                  <td className="p-4 font-medium">{user.username}</td>
                  <td className="p-4 text-text-muted">{user.email}</td>
                  <td className="p-4">
                    <span
                      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                        user.user_type === "escort"
                          ? "bg-pink-500/20 text-pink-400"
                          : user.user_type === "admin"
                          ? "bg-red-500/20 text-red-400"
                          : "bg-blue-500/20 text-blue-400"
                      }`}
                    >
                      {user.user_type}
                    </span>
                  </td>
                  <td className="p-4 text-text-muted">
                    {user.country?.name ?? "-"}
                  </td>
                  <td className="p-4">
                    <div className="space-y-1">
                      <span className="flex items-center gap-2 text-sm">
                        <span
                          className={`inline-block w-2 h-2 rounded-full ${
                            user.active ? "bg-green-400" : "bg-red-400"
                          }`}
                        />
                        {user.active ? "Active" : "Inactive"}
                      </span>
                      <span
                        className={`block text-xs ${
                          user.is_verified ? "text-green-400" : "text-text-muted"
                        }`}
                      >
                        {user.is_verified ? "Verified" : "Unverified"}
                      </span>
                    </div>
                  </td>
                  <td className="p-4 text-text-muted text-sm whitespace-nowrap">
                    {user.lastonline_at
                      ? new Date(user.lastonline_at).toLocaleDateString()
                      : "Never"}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {new Date(user.created_at).toLocaleDateString()}
                  </td>
                  <td className="p-4">
                    <div className="flex gap-2">
                      <Link
                        href={`/admin/users/${user.id}`}
                        className="text-text-muted hover:text-white text-sm transition-colors"
                      >
                        View
                      </Link>
                      <Link
                        href={`/admin/users/${user.id}`}
                        className="text-primary hover:text-primary-dark text-sm transition-colors"
                      >
                        Edit
                      </Link>
                    </div>
                  </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>
  );
}
