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

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

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

  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;

  // Count unique customers who logged in last 30 days
  const last30DaysLogs = logs.filter(
    (l) => l.loginAt > new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) && l.success && l.customerId
  );
  const uniqueCustomers = new Set(last30DaysLogs.map((l) => l.customerId)).size;

  // Get most active customers
  const successfulLogs = logs.filter((l) => l.success && l.customerId);
  const customerCounts = new Map<string | null, { email: string; count: number }>();

  successfulLogs.forEach((log) => {
    const existing = customerCounts.get(log.customerId) || { email: log.email, count: 0 };
    customerCounts.set(log.customerId, { email: existing.email || log.email, count: existing.count + 1 });
  });

  const mostActiveCustomers = Array.from(customerCounts.values())
    .sort((a, b) => b.count - a.count)
    .slice(0, 10);

  return (
    <div className="mx-auto max-w-5xl px-6 py-12">
      <AdminNav />
      <div className="flex flex-wrap items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Customer 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 customer account access attempts. Track login patterns and identify unusual activity.
      </p>

      {/* Stats */}
      <div className="mt-6 grid gap-3 sm:grid-cols-4">
        <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 className="border border-line bg-surface p-4">
          <p className="tag-label">Active Customers</p>
          <p className="mt-1 font-mono text-xl">{uniqueCustomers}</p>
        </div>
      </div>

      {/* Most Active Customers */}
      <div className="mt-8">
        <h2 className="font-display text-2xl">Most Active Customers</h2>
        {mostActiveCustomers.length === 0 ? (
          <p className="mt-4 text-sm text-muted">No customer logins recorded yet.</p>
        ) : (
          <div className="mt-4 grid gap-3 sm:grid-cols-2">
            {mostActiveCustomers.map((customer, idx) => (
              <div key={idx} className="border border-line bg-surface p-4">
                <p className="tag-label mb-1">{idx + 1}. {customer.email}</p>
                <p className="font-mono text-lg">{customer.count} logins</p>
              </div>
            ))}
          </div>
        )}
      </div>

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

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