import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { IpBanActions, IpBanForm } from "./IpBanActions";

interface IpBanRow {
  id: number;
  ip_address: string;
  reason: string | null;
  banned_by: number | null;
  banned_by_username: string | null;
  expires_at: Date | null;
  created_at: Date;
}

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

  let bans: IpBanRow[] = [];
  try {
    bans = await prisma.$queryRawUnsafe(
      `SELECT ib.*, u.username as banned_by_username
       FROM ip_bans ib
       LEFT JOIN users u ON ib.banned_by = u.id
       ORDER BY ib.created_at DESC`
    );
  } catch (e) {
    console.error("Failed to load IP bans:", e);
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">IP Ban Management</h1>

      {/* Add Ban Form */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Add IP Ban</h2>
        <IpBanForm />
      </div>

      {/* Bans Table */}
      <div className="bg-surface rounded-lg 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">IP Address</th>
              <th className="p-4 font-medium">Reason</th>
              <th className="p-4 font-medium">Banned By</th>
              <th className="p-4 font-medium">Expires</th>
              <th className="p-4 font-medium">Created</th>
              <th className="p-4 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {bans.length === 0 ? (
              <tr>
                <td colSpan={6} className="p-4 text-center text-text-muted">
                  No IP bans.
                </td>
              </tr>
            ) : (
              bans.map((ban) => (
                <tr
                  key={ban.id}
                  className="border-b border-surface-light last:border-0"
                >
                  <td className="p-4 font-mono text-sm">{ban.ip_address}</td>
                  <td className="p-4 text-text-muted text-sm max-w-[200px] truncate">
                    {ban.reason || "-"}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {ban.banned_by_username || (ban.banned_by ? `#${ban.banned_by}` : "-")}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {ban.expires_at
                      ? new Date(ban.expires_at).toLocaleString()
                      : "Never"}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {new Date(ban.created_at).toLocaleString()}
                  </td>
                  <td className="p-4">
                    <IpBanActions banId={ban.id} />
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
