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

export default async function AdminAgenciesPage() {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  let agencies: {
    id: number;
    username: string | null;
    email: string;
    city_id: number | null;
    country_id: number | null;
    active: boolean;
    created_at: Date;
  }[] = [];

  try {
    agencies = await prisma.user.findMany({
      where: { is_agency: true },
      select: {
        id: true,
        username: true,
        email: true,
        city_id: true,
        country_id: true,
        active: true,
        created_at: true,
      },
      orderBy: { created_at: "desc" },
    });
  } catch (e) {
    console.error("Failed to load agencies:", e);
  }

  // Get escort counts and gallery/photo stats per agency city
  const agencyStats: Record<
    number,
    { escortCount: number; galleryCount: number; photoCount: number }
  > = {};

  for (const agency of agencies) {
    try {
      // Escorts in same city (placeholder logic)
      const escortCount = agency.city_id
        ? await prisma.user.count({
            where: {
              city_id: agency.city_id,
              user_type: "escort",
              is_agency: false,
            },
          })
        : 0;

      // Gallery and photo counts for those escorts
      let galleryCount = 0;
      let photoCount = 0;
      if (agency.city_id) {
        const escortIds = await prisma.user.findMany({
          where: {
            city_id: agency.city_id,
            user_type: "escort",
            is_agency: false,
          },
          select: { id: true },
        });
        const ids = escortIds.map((e) => e.id);
        if (ids.length > 0) {
          galleryCount = await prisma.gallery.count({
            where: { user_id: { in: ids } },
          }).catch(() => 0);
          photoCount = await prisma.photo.count({
            where: { user_id: { in: ids } },
          }).catch(() => 0);
        }
      }

      agencyStats[agency.id] = { escortCount, galleryCount, photoCount };
    } catch (e) {
      console.error(`Failed to load stats for agency ${agency.id}:`, e);
      agencyStats[agency.id] = { escortCount: 0, galleryCount: 0, photoCount: 0 };
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Agencies</h1>
        <span className="text-text-muted text-sm">
          {agencies.length} agencies
        </span>
      </div>

      <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">Email</th>
                <th className="p-4 font-medium">Escorts</th>
                <th className="p-4 font-medium">Galleries</th>
                <th className="p-4 font-medium">Photos</th>
                <th className="p-4 font-medium">Status</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {agencies.length === 0 && (
                <tr>
                  <td
                    colSpan={8}
                    className="p-8 text-center text-text-muted"
                  >
                    No agencies found
                  </td>
                </tr>
              )}
              {agencies.map((agency) => {
                const stats = agencyStats[agency.id] || {
                  escortCount: 0,
                  galleryCount: 0,
                  photoCount: 0,
                };
                return (
                  <tr
                    key={agency.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">
                      {agency.id}
                    </td>
                    <td className="p-4 font-medium">
                      {agency.username || "—"}
                    </td>
                    <td className="p-4 text-text-muted text-sm">
                      {agency.email}
                    </td>
                    <td className="p-4">{stats.escortCount}</td>
                    <td className="p-4">{stats.galleryCount}</td>
                    <td className="p-4">{stats.photoCount}</td>
                    <td className="p-4">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          agency.active
                            ? "bg-green-500/20 text-green-400"
                            : "bg-red-500/20 text-red-400"
                        }`}
                      >
                        {agency.active ? "Active" : "Inactive"}
                      </span>
                    </td>
                    <td className="p-4">
                      <Link
                        href={`/admin/agencies/${agency.id}`}
                        className="text-primary hover:text-primary-dark text-sm transition-colors"
                      >
                        Manage
                      </Link>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
