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

export default async function AdminUserDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const { id } = await params;
  const userId = parseInt(id);
  if (isNaN(userId)) redirect("/admin/users");

  // E.10: only super-admins see the full IP. Regular admins see a masked
  // form (last octet/group dropped) for data-minimisation hygiene.
  const adminId = parseInt(session.user.id);
  const superAdminAllowList = (process.env.SUPER_ADMIN_USER_IDS || "")
    .split(",")
    .map((s) => Number(s.trim()))
    .filter((n) => Number.isInteger(n) && n > 0);
  const isSuperAdmin = superAdminAllowList.includes(adminId);
  function maskIp(ip: string | null | undefined): string {
    if (!ip) return "-";
    if (isSuperAdmin) return ip;
    if (ip.includes(":")) {
      const parts = ip.split(":");
      return parts.slice(0, parts.length - 1).join(":") + ":·";
    }
    const parts = ip.split(".");
    if (parts.length === 4) return `${parts[0]}.${parts[1]}.${parts[2]}.·`;
    return "·";
  }

  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      country: true,
      city: true,
      credit: true,
      characteristic: {
        include: {
          gender: true,
          age: true,
          orientation: true,
          ethnicity: true,
          nationality: true,
          height: true,
          weight: true,
          eye_color: true,
          hair_color: true,
          hair_length: true,
          hair_public: true,
          breast_size: true,
          breast_state: true,
          cup_size: true,
          smoking: true,
          travel: true,
          calling: true,
        },
      },
    },
  });

  if (!user) redirect("/admin/users");

  const [photos, galleries, photosCount, galleriesCount, auditLogs] =
    await Promise.all([
      prisma.photo.findMany({
        where: { user_id: userId },
        orderBy: { created_at: "desc" },
        take: 10,
      }),
      prisma.gallery.findMany({
        where: { user_id: userId },
        orderBy: { created_at: "desc" },
        take: 5,
        include: { _count: { select: { photos: true } } },
      }),
      prisma.photo.count({ where: { user_id: userId } }),
      prisma.gallery.count({ where: { user_id: userId } }),
      prisma.auditLog.findMany({
        where: { target_type: "User", target_id: userId },
        orderBy: { created_at: "desc" },
        take: 20,
      }),
    ]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            href="/admin/users"
            className="text-text-muted hover:text-white transition-colors"
          >
            &larr; Back
          </Link>
          <h1 className="text-2xl font-bold">
            {user.username || "Unnamed User"}{" "}
            <span className="text-text-muted font-normal text-lg">
              #{user.id}
            </span>
          </h1>
        </div>
        <UserActions
          userId={user.id}
          isVerified={user.is_verified}
          isBanned={!!user.banned_at}
          isSuspended={
            !!user.suspended_until && user.suspended_until > new Date()
          }
          userType={user.user_type}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Basic Info */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Basic Info</h2>
          <dl className="space-y-3">
            <div className="flex justify-between">
              <dt className="text-text-muted">Email</dt>
              <dd>{user.email}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Username</dt>
              <dd>{user.username || "-"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Type</dt>
              <dd>
                <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>
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">ID (AW)</dt>
              <dd className="font-mono text-sm">{user.id_aw || "-"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Gender</dt>
              <dd>{user.characteristic?.gender?.name || "-"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Born</dt>
              <dd>
                {user.born_at
                  ? new Date(user.born_at).toLocaleDateString()
                  : "-"}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Credits</dt>
              <dd className="font-medium">
                {user.credit?.credits ?? 0}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Hits</dt>
              <dd>{user.hits}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Registered</dt>
              <dd className="text-sm">
                {new Date(user.created_at).toLocaleString()}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Last Online</dt>
              <dd className="text-sm">
                {user.lastonline_at
                  ? new Date(user.lastonline_at).toLocaleString()
                  : "-"}
              </dd>
            </div>
          </dl>
        </div>

        {/* Location */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Location</h2>
          <dl className="space-y-3">
            <div className="flex justify-between">
              <dt className="text-text-muted">Country</dt>
              <dd>{user.country?.name || "-"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">City</dt>
              <dd>{user.city?.name || "-"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">IP Address</dt>
              <dd className="font-mono text-sm" title={isSuperAdmin ? "Full IP visible (super-admin)" : "Masked — only super-admins see the full IP"}>{maskIp(user.ip_address)}</dd>
            </div>
          </dl>

          <h2 className="text-lg font-semibold mb-4 mt-8">
            Verification Status
          </h2>
          <dl className="space-y-3">
            <div className="flex justify-between">
              <dt className="text-text-muted">Verified</dt>
              <dd>
                {user.is_verified ? (
                  <span className="text-green-400">Yes</span>
                ) : (
                  <span className="text-red-400">No</span>
                )}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Email Verified</dt>
              <dd>
                {user.email_verified_at ? (
                  <span className="text-green-400">
                    {new Date(user.email_verified_at).toLocaleDateString()}
                  </span>
                ) : (
                  <span className="text-red-400">No</span>
                )}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">VIP</dt>
              <dd>{user.is_vip ? "Yes" : "No"}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Top</dt>
              <dd>{user.is_top ? "Yes" : "No"}</dd>
            </div>
          </dl>
        </div>

        {/* Account Status */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Account Status</h2>
          <dl className="space-y-3">
            <div className="flex justify-between">
              <dt className="text-text-muted">Active</dt>
              <dd>
                {user.active ? (
                  <span className="text-green-400">Yes</span>
                ) : (
                  <span className="text-red-400">No</span>
                )}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Banned</dt>
              <dd>
                {user.banned_at ? (
                  <span className="text-red-400">
                    {new Date(user.banned_at).toLocaleDateString()}
                  </span>
                ) : (
                  <span className="text-green-400">No</span>
                )}
              </dd>
            </div>
            {user.ban_reason && (
              <div className="flex justify-between">
                <dt className="text-text-muted">Ban Reason</dt>
                <dd className="text-red-400 text-sm max-w-[200px] text-right">
                  {user.ban_reason}
                </dd>
              </div>
            )}
            <div className="flex justify-between">
              <dt className="text-text-muted">Suspended Until</dt>
              <dd>
                {user.suspended_until ? (
                  <span className="text-yellow-400">
                    {new Date(user.suspended_until).toLocaleString()}
                  </span>
                ) : (
                  <span className="text-green-400">No</span>
                )}
              </dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Photos</dt>
              <dd>{photosCount}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-text-muted">Galleries</dt>
              <dd>{galleriesCount}</dd>
            </div>
          </dl>
        </div>

        {/* Characteristics */}
        {user.characteristic && (
          <div className="bg-surface rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">Characteristics</h2>
            <dl className="space-y-3">
              {[
                ["Ethnicity", user.characteristic.ethnicity?.name],
                ["Nationality", user.characteristic.nationality?.name],
                ["Orientation", user.characteristic.orientation?.name],
                ["Age Range", user.characteristic.age?.name],
                ["Height", user.characteristic.height?.name],
                ["Weight", user.characteristic.weight?.name],
                ["Eye Color", user.characteristic.eye_color?.name],
                ["Hair Color", user.characteristic.hair_color?.name],
                ["Hair Length", user.characteristic.hair_length?.name],
                ["Breast Size", user.characteristic.breast_size?.name],
                ["Cup Size", user.characteristic.cup_size?.name],
                ["Smoking", user.characteristic.smoking?.name],
                ["Travel", user.characteristic.travel?.name],
              ]
                .filter(([, v]) => v)
                .map(([label, value]) => (
                  <div key={label} className="flex justify-between">
                    <dt className="text-text-muted">{label}</dt>
                    <dd>{value}</dd>
                  </div>
                ))}
            </dl>
          </div>
        )}
      </div>

      {/* Recent Photos */}
      {photos.length > 0 && (
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">
            Recent Photos ({photosCount} total)
          </h2>
          <div className="grid grid-cols-5 md:grid-cols-10 gap-3">
            {photos.map((photo) => (
              <div key={photo.id} className="relative group">
                <img
                  src={photoUrl(photo.photo, user.id_aw)}
                  alt=""
                  className="w-full aspect-square object-cover rounded-lg"
                />
                <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-xs p-1 rounded-b-lg text-center">
                  <span
                    className={
                      photo.moderation_status === "approved"
                        ? "text-green-400"
                        : photo.moderation_status === "rejected"
                        ? "text-red-400"
                        : "text-yellow-400"
                    }
                  >
                    {photo.moderation_status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Recent Galleries */}
      {galleries.length > 0 && (
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">
            Recent Galleries ({galleriesCount} total)
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            {galleries.map((gallery) => (
              <div
                key={gallery.id}
                className="bg-surface-light rounded-lg p-4"
              >
                <p className="font-medium truncate">{gallery.name}</p>
                <p className="text-text-muted text-sm">
                  {gallery._count.photos} photos
                </p>
                <p className="text-text-muted text-xs mt-1">
                  {gallery.private ? "Private" : "Public"} &middot;{" "}
                  {gallery.credits} credits
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Audit Log */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Audit Log</h2>
        {auditLogs.length === 0 ? (
          <p className="text-text-muted">No audit log entries for this user.</p>
        ) : (
          <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="pb-3 font-medium">Admin ID</th>
                  <th className="pb-3 font-medium">Action</th>
                  <th className="pb-3 font-medium">Details</th>
                  <th className="pb-3 font-medium">Date</th>
                </tr>
              </thead>
              <tbody>
                {auditLogs.map((log) => (
                  <tr
                    key={log.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-text-muted">{log.admin_id}</td>
                    <td className="py-3">
                      <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-surface-light">
                        {log.action}
                      </span>
                    </td>
                    <td className="py-3 text-text-muted text-sm max-w-[300px] truncate">
                      {log.details || "-"}
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(log.created_at).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
