import { redirect } from "next/navigation";
import Link from "next/link";
import { AdminLogoutButton } from "@/components/admin/AdminLogoutButton";
import { getAdminSession } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

async function getStats() {
  try {
    const [usageCount, feedbackCount, userCount, visitCount, topTools, topPages, referrers, languages, timezones, devices] =
      await Promise.all([
        prisma.toolUsage.count(),
        prisma.toolFeedback.count(),
        prisma.user.count(),
        prisma.siteVisit.count(),
        prisma.toolUsage.groupBy({
          by: ["toolSlug"],
          _count: { toolSlug: true },
          orderBy: { _count: { toolSlug: "desc" } },
          take: 5,
        }),
        prisma.siteVisit.groupBy({
          by: ["path"],
          _count: { path: true },
          orderBy: { _count: { path: "desc" } },
          take: 8,
        }),
        prisma.siteVisit.groupBy({
          by: ["referrerHost"],
          where: { referrerHost: { not: null } },
          _count: { referrerHost: true },
          orderBy: { _count: { referrerHost: "desc" } },
          take: 8,
        }),
        prisma.siteVisit.groupBy({
          by: ["language"],
          where: { language: { not: null } },
          _count: { language: true },
          orderBy: { _count: { language: "desc" } },
          take: 8,
        }),
        prisma.siteVisit.groupBy({
          by: ["timezone"],
          where: { timezone: { not: null } },
          _count: { timezone: true },
          orderBy: { _count: { timezone: "desc" } },
          take: 8,
        }),
        prisma.siteVisit.groupBy({
          by: ["deviceType"],
          where: { deviceType: { not: null } },
          _count: { deviceType: true },
          orderBy: { _count: { deviceType: "desc" } },
          take: 8,
        }),
      ]);

    return {
      usageCount,
      feedbackCount,
      userCount,
      visitCount,
      topTools,
      topPages,
      referrers,
      languages,
      timezones,
      devices,
    };
  } catch {
    return null;
  }
}

export default async function AdminPage() {
  const session = await getAdminSession();
  if (!session) redirect("/admin/login");

  const stats = await getStats();

  return (
    <div className="container mx-auto max-w-5xl px-4 py-16">
      <div className="mb-6 flex items-center gap-2">
        <div className="h-2 w-2 rounded-full bg-green-500" />
        <span className="text-xs text-gray-400">Admin - angemeldet als {session.email}</span>
      </div>

      <div className="mb-8 flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold text-gray-900">Admin Dashboard</h1>
        <AdminLogoutButton />
      </div>
      <div className="mb-8 flex flex-wrap gap-3">
        <Link
          href="/admin/newsletter"
          className="inline-flex rounded-lg bg-gray-950 px-4 py-2 text-sm font-bold text-white hover:bg-blue-600"
        >
          Newsletter verwalten
        </Link>
      </div>

      {!stats ? (
        <div className="rounded-lg border bg-red-50 p-4 text-sm text-red-600">
          Datenbankverbindung fehlgeschlagen. Bitte DB-Migration ausführen: <code>npm run db:migrate</code>
        </div>
      ) : (
        <>
          <div className="grid gap-4 sm:grid-cols-4 mb-8">
            <StatCard label="Besuche" value={stats.visitCount} />
            <StatCard label="Tool-Nutzungen" value={stats.usageCount} />
            <StatCard label="Feedbacks" value={stats.feedbackCount} />
            <StatCard label="User" value={stats.userCount} />
          </div>

          <div className="grid gap-6 lg:grid-cols-2">
            <MetricList
              title="Top Seiten"
              items={stats.topPages.map((item) => ({
                label: item.path,
                value: item._count.path,
              }))}
            />
            <MetricList
              title="Referrer"
              items={stats.referrers.map((item) => ({
                label: item.referrerHost ?? "direct",
                value: item._count.referrerHost,
              }))}
            />
            <MetricList
              title="Sprachen"
              items={stats.languages.map((item) => ({
                label: item.language ?? "unknown",
                value: item._count.language,
              }))}
            />
            <MetricList
              title="Zeitzonen"
              items={stats.timezones.map((item) => ({
                label: item.timezone ?? "unknown",
                value: item._count.timezone,
              }))}
            />
            <MetricList
              title="Geräte"
              items={stats.devices.map((item) => ({
                label: item.deviceType ?? "unknown",
                value: item._count.deviceType,
              }))}
            />
            <MetricList
              title="Top Tools"
              items={stats.topTools.map((item) => ({
                label: item.toolSlug,
                value: item._count.toolSlug,
              }))}
            />
          </div>
        </>
      )}
    </div>
  );
}

function StatCard({ label, value }: { label: string; value: number }) {
  return (
    <div className="rounded-xl border p-5 text-center">
      <div className="text-3xl font-bold text-blue-600">{value}</div>
      <div className="text-sm text-gray-500 mt-1">{label}</div>
    </div>
  );
}

function MetricList({ title, items }: { title: string; items: { label: string; value: number }[] }) {
  return (
    <section className="rounded-xl border bg-white p-5">
      <h2 className="mb-4 text-lg font-semibold text-gray-950">{title}</h2>
      {items.length ? (
        <div className="space-y-2">
          {items.map((item) => (
            <div key={item.label} className="flex items-center justify-between gap-3 rounded-lg bg-gray-50 p-3 text-sm">
              <span className="break-all font-medium text-gray-700">{item.label}</span>
              <span className="shrink-0 text-gray-500">{item.value}</span>
            </div>
          ))}
        </div>
      ) : (
        <p className="text-sm text-gray-400">Noch keine Daten.</p>
      )}
    </section>
  );
}
