import { prisma } from '@/lib/prisma';
import { isAdminAuthenticated } from '@/lib/adminAuth';
import AdminNav from '@/components/AdminNav';
import Link from 'next/link';
import CollapsibleAdminLoginTable from '@/components/CollapsibleAdminLoginTable';

export default async function LoginLogsPage() {
  const isAdmin = await isAdminAuthenticated();
  if (!isAdmin) {
    return <div className="px-6 py-12 text-center">Unauthorized</div>;
  }

  const logs = await prisma.adminLoginLog.findMany({
    orderBy: { loginAt: 'desc' },
    take: 100,
  });

  const successCount = logs.filter((l) => l.success).length;
  const failureCount = logs.filter((l) => !l.success).length;
  const last30Days = logs.filter(
    (l) => l.loginAt > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
  ).length;

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <div className="flex flex-wrap items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Admin Login Activity</h1>
        <Link href="/admin/orders" className="text-sm text-clay hover:text-clay-dark">
          Back to orders
        </Link>
      </div>

      <p className="mt-4 text-sm text-muted">
        Record of admin panel access attempts. IP addresses and user agents are logged for security.
      </p>

      {/* Stats */}
      <div className="mt-6 grid gap-3 sm:grid-cols-3">
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Successful Logins</p>
          <p className="mt-1 font-mono text-xl">{successCount}</p>
        </div>
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Failed Attempts</p>
          <p className="mt-1 font-mono text-xl">{failureCount}</p>
        </div>
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Last 30 Days</p>
          <p className="mt-1 font-mono text-xl">{last30Days}</p>
        </div>
      </div>

      {/* Recent Logins - Collapsible */}
      <div className="mt-8">
        <h2 className="font-display text-2xl mb-4">Recent Login Activity</h2>
        <CollapsibleAdminLoginTable logs={logs} />
      </div>

      <p className="mt-8 text-xs text-muted">
        Showing last 100 login attempts. Recent activity shows only the last 10 logins.
      </p>
    </div>
  );
}
