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

interface VerificationLog {
  id: number;
  session_id: string;
  user_id: number | null;
  ip_address: string;
  country: string;
  method: string;
  status: string;
  created_at: Date;
  updated_at: Date;
}

interface StatRow {
  status: string;
  count: bigint;
}

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

  let logs: VerificationLog[] = [];
  let stats: StatRow[] = [];

  try {
    logs = await prisma.$queryRawUnsafe<VerificationLog[]>(
      `SELECT id, session_id, user_id, ip_address, country, method, status, created_at, updated_at
       FROM age_verification_logs
       ORDER BY created_at DESC
       LIMIT 100`
    );

    stats = await prisma.$queryRawUnsafe<StatRow[]>(
      `SELECT status, COUNT(*) as count
       FROM age_verification_logs
       GROUP BY status`
    );
  } catch {
    // Table may not exist yet
  }

  const statMap: Record<string, number> = {};
  for (const s of stats) {
    statMap[s.status] = Number(s.count);
  }
  const totalVerified = statMap["verified"] || 0;
  const totalPending = statMap["pending"] || 0;
  const totalFailed = statMap["failed"] || 0;

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Age Verification (UK OSA)</h1>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-surface rounded-lg p-5 border border-surface-light">
          <p className="text-text-muted text-sm mb-1">Verified</p>
          <p className="text-2xl font-bold text-green-400">{totalVerified}</p>
        </div>
        <div className="bg-surface rounded-lg p-5 border border-surface-light">
          <p className="text-text-muted text-sm mb-1">Pending</p>
          <p className="text-2xl font-bold text-yellow-400">{totalPending}</p>
        </div>
        <div className="bg-surface rounded-lg p-5 border border-surface-light">
          <p className="text-text-muted text-sm mb-1">Failed</p>
          <p className="text-2xl font-bold text-red-400">{totalFailed}</p>
        </div>
      </div>

      {/* Logs 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">User ID</th>
              <th className="p-4 font-medium">IP Address</th>
              <th className="p-4 font-medium">Country</th>
              <th className="p-4 font-medium">Method</th>
              <th className="p-4 font-medium">Status</th>
              <th className="p-4 font-medium">Date</th>
            </tr>
          </thead>
          <tbody>
            {logs.length === 0 ? (
              <tr>
                <td
                  colSpan={6}
                  className="p-12 text-center text-text-muted"
                >
                  <div className="flex flex-col items-center gap-3">
                    <svg className="w-10 h-10 text-text-muted/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                    </svg>
                    <p className="text-sm font-medium">No verification logs yet</p>
                    <p className="text-xs text-text-muted/70">
                      Age verification logs will appear here once users begin verifying their age.
                      The <code className="bg-zinc-700 px-1 py-0.5 rounded">age_verification_logs</code> table
                      will be populated automatically.
                    </p>
                  </div>
                </td>
              </tr>
            ) : (
              logs.map((log) => (
                <tr
                  key={log.id}
                  className="border-b border-surface-light hover:bg-surface-light/50 transition-colors"
                >
                  <td className="p-4 text-sm">
                    {log.user_id || (
                      <span className="text-zinc-500">anonymous</span>
                    )}
                  </td>
                  <td className="p-4 text-sm font-mono text-xs">
                    {log.ip_address}
                  </td>
                  <td className="p-4 text-sm">{log.country}</td>
                  <td className="p-4 text-sm capitalize">{log.method}</td>
                  <td className="p-4 text-sm">
                    <span
                      className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                        log.status === "verified"
                          ? "bg-green-500/10 text-green-400"
                          : log.status === "pending"
                            ? "bg-yellow-500/10 text-yellow-400"
                            : "bg-red-500/10 text-red-400"
                      }`}
                    >
                      {log.status}
                    </span>
                  </td>
                  <td className="p-4 text-sm text-text-muted">
                    {new Date(log.created_at).toLocaleString(undefined)}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
