import { db } from "@/db/client";
import { desiredStates, mediaItems, storageAvailability, storageTiers, users, watchingNowItems, watchlistItems } from "@/db/schema";
import { count, desc, eq, isNull } from "drizzle-orm";
import Link from "next/link";

export const dynamic = "force-dynamic";

function formatDate(value: Date | null) {
  return value ? value.toISOString().slice(0, 16).replace("T", " ") : "Open";
}

export default async function AdminDashboard() {
  const [
    [{ userCount }],
    [{ watchingNowCount }],
    [{ watchlistCount }],
    [{ desiredStateCount }],
    recentDemand,
    tiers,
    availabilityRows,
  ] = await Promise.all([
    db.select({ userCount: count() }).from(users),
    db.select({ watchingNowCount: count() }).from(watchingNowItems).where(isNull(watchingNowItems.removedAt)),
    db.select({ watchlistCount: count() }).from(watchlistItems).where(isNull(watchlistItems.removedAt)),
    db.select({ desiredStateCount: count() }).from(desiredStates),
    db
      .select({
        id: watchingNowItems.id,
        title: mediaItems.title,
        mediaType: mediaItems.mediaType,
        displayName: users.displayName,
        addedAt: watchingNowItems.addedAt,
      })
      .from(watchingNowItems)
      .innerJoin(users, eq(users.id, watchingNowItems.userId))
      .innerJoin(mediaItems, eq(mediaItems.id, watchingNowItems.mediaItemId))
      .where(isNull(watchingNowItems.removedAt))
      .orderBy(desc(watchingNowItems.addedAt))
      .limit(5),
    db.select().from(storageTiers).orderBy(storageTiers.tier),
    db.select().from(storageAvailability).orderBy(desc(storageAvailability.detectedAt)).limit(20),
  ]);

  const latestAvailability = new Map<string, (typeof availabilityRows)[number]>();
  for (const row of availabilityRows) {
    if (!latestAvailability.has(row.tierId)) {
      latestAvailability.set(row.tierId, row);
    }
  }

  const stats = [
    { label: "Users", value: userCount, href: "/admin/users" },
    { label: "Watching Now", value: watchingNowCount, href: "/admin/demand" },
    { label: "Watchlist", value: watchlistCount, href: "/admin/demand" },
    { label: "Desired states", value: desiredStateCount, href: "/admin/policy" },
  ];

  return (
    <div className="space-y-8">
      <div>
        <p className="text-xs font-semibold uppercase tracking-[0.32em] text-admin-accent">Control plane</p>
        <h1 className="mt-2 font-serif text-3xl font-semibold">Admin Dashboard</h1>
      </div>

      <div className="grid grid-cols-2 gap-4 xl:grid-cols-4">
        {stats.map((stat) => (
          <Link key={stat.label} href={stat.href} className="admin-card block p-4">
            <p className="text-sm text-admin-muted">{stat.label}</p>
            <p className="mt-2 text-3xl font-bold">{stat.value}</p>
          </Link>
        ))}
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
        <section className="admin-panel p-5">
          <div className="mb-4 flex items-center justify-between gap-4">
            <h2 className="font-serif text-xl font-semibold">Recent Watching Now</h2>
            <Link href="/admin/demand" className="text-sm font-medium text-admin-accent hover:text-admin-text">View demand</Link>
          </div>
          <div className="divide-y divide-admin-line">
            {recentDemand.length ? recentDemand.map((item) => (
              <div key={item.id} className="grid gap-2 py-3 sm:grid-cols-[1fr_auto] sm:items-center">
                <div>
                  <p className="font-medium">{item.title}</p>
                  <p className="text-sm text-admin-muted">{item.displayName} · {item.mediaType === "movie" ? "Movie" : "TV"}</p>
                </div>
                <p className="text-sm text-admin-muted">{formatDate(item.addedAt)}</p>
              </div>
            )) : <p className="text-sm text-admin-muted">No active Watching Now items yet.</p>}
          </div>
        </section>

        <section className="admin-panel p-5">
          <div className="mb-4 flex items-center justify-between gap-4">
            <h2 className="font-serif text-xl font-semibold">Storage Tiers</h2>
            <Link href="/admin/storage" className="text-sm font-medium text-admin-accent hover:text-admin-text">View storage</Link>
          </div>
          <div className="space-y-3">
            {tiers.length ? tiers.map((tier) => {
              const latest = latestAvailability.get(tier.id);
              const online = tier.alwaysOnline || latest?.online;
              return (
                <div key={tier.id} className="rounded-md border border-admin-line bg-admin-subpanel p-3">
                  <div className="flex items-center justify-between gap-3">
                    <p className="font-medium">{tier.label}</p>
                    <span className={online ? "text-sm font-medium text-admin-good" : "text-sm font-medium text-admin-muted"}>{online ? "Online" : "Offline"}</span>
                  </div>
                  <p className="mt-1 truncate text-sm text-admin-muted">{tier.basePath}</p>
                </div>
              );
            }) : <p className="text-sm text-admin-muted">No storage tiers configured yet.</p>}
          </div>
        </section>
      </div>
    </div>
  );
}
