import * as React from "react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { getAdminSession } from "@/lib/admin/auth";
import { db } from "@/lib/admin/db";
import { getUserPermissions } from "@/lib/admin/permissions";
import {
  Users,
  KeyRound,
  ShieldCheck,
  History,
  ArrowRight,
  ShieldAlert,
  FileText,
  Clock,
  Sparkles,
  Image as ImageIcon,
  ArrowRightLeft,
  ExternalLink,
  Plus,
} from "lucide-react";

export const dynamic = "force-dynamic";

export default async function AdminDashboardPage() {
  const ctx = await getAdminSession();

  if (!ctx) {
    redirect("/admin/login");
  }

  const { user } = ctx;

  if (user.passwordChangeRequired) {
    redirect("/admin/change-password");
  }

  const isMainAdmin = user.level === "MAIN_ADMIN";
  const permissions = getUserPermissions(user);

  // Fetch all independent dashboard metrics in parallel (eliminating sequential waterfalls)
  const [
    allUsers,
    allSessions,
    allResetRequests,
    recentSecurityLogs,
    recentContentLogs,
    publishedCount,
    scheduledCount,
    draftCount,
    mediaItems,
  ] = await Promise.all([
    db.getUsers(),
    db.getSessions(),
    isMainAdmin ? db.getResetRequests() : Promise.resolve([]),
    isMainAdmin ? db.getSecurityLogs({ limit: 5 }) : Promise.resolve([]),
    db.getContentLogs({ limit: 6 }),
    db.getPostCount({ status: "PUBLISHED" }),
    db.getPostCount({ status: "SCHEDULED" }),
    db.getPostCount({ status: "DRAFT" }),
    db.getMedia("", 500),
  ]);

  const subAdmins = allUsers.filter((u) => u.level === "SUB_ADMIN");
  const activeSubAdmins = subAdmins.filter((u) => u.status === "ACTIVE");

  const now = new Date().toISOString();
  const nowMs = Date.now();
  const inactivityLimitMs = 120 * 60 * 1000; // 2 hours
  const activeSessions = allSessions.filter((s) => {
    if (s.revoked || s.status === "REVOKED" || s.status === "EXPIRED" || s.status === "BLOCKED") return false;
    if (s.expiresAt <= now) return false;
    const lastSeenMs = new Date(s.lastSeenAt || s.lastActiveAt || s.createdAt).getTime();
    if (nowMs - lastSeenMs > inactivityLimitMs) return false;
    return true;
  });

  const pendingResets = allResetRequests.filter(
    (r) => r.status === "PENDING" && r.expiresAt > now
  );
  const mediaCount = mediaItems.length;

  return (
    <div className="space-y-8">
      {/* Header Banner */}
      <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="font-bold text-2xl tracking-tight text-neutral-900 dark:text-white">
              System Overview
            </h1>
            <span
              className={`rounded-full px-2.5 py-0.5 text-[10px] font-bold tracking-wider uppercase ${
                isMainAdmin
                  ? "bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"
                  : "bg-neutral-200 text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200"
              }`}
            >
              {isMainAdmin ? "Main Admin Authority" : (user.role || "SUB_ADMIN").replace(/_/g, " ")}
            </span>
          </div>
          <p className="text-xs text-neutral-500">
            {isMainAdmin
              ? "Live overview of administrative access, security controls, and editorial activity."
              : `Signed in as ${user.name}. You are authorized for ${(user.role || "sub_admin").replace(/_/g, " ").toLowerCase()} actions.`}
          </p>
        </div>

        {isMainAdmin && (
          <div className="flex items-center gap-2.5">
            <Link
              href="/admin/admins"
              className="flex h-9 items-center gap-1.5 rounded-lg bg-neutral-900 px-3.5 text-xs font-semibold text-white shadow-xs transition hover:bg-neutral-800 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-100"
            >
              <Users className="h-3.5 w-3.5" />
              <span>Create Sub-admin</span>
            </Link>
          </div>
        )}
      </div>

      {/* Metric Cards (Main Admin vs Sub-Admin) */}
      {isMainAdmin ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Total Administrators</span>
              <Users className="h-4 w-4" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {allUsers.length}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400">
              {activeSubAdmins.length} active sub-admin{activeSubAdmins.length === 1 ? "" : "s"}
            </div>
          </div>

          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Reset Requests</span>
              <KeyRound className="h-4 w-4" />
            </div>
            <div className="mt-3 flex items-baseline gap-2">
              <span className="font-bold text-2xl text-neutral-900 dark:text-white">
                {pendingResets.length}
              </span>
              {pendingResets.length > 0 && (
                <span className="rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-bold text-amber-800 dark:bg-amber-950 dark:text-amber-300">
                  Pending Review
                </span>
              )}
            </div>
            <div className="mt-1 text-[11px]">
              {pendingResets.length > 0 ? (
                <Link
                  href="/admin/security/reset-requests"
                  className="font-medium text-amber-600 hover:underline dark:text-amber-400"
                >
                  Review requests &rarr;
                </Link>
              ) : (
                <span className="text-neutral-400">Queue clear</span>
              )}
            </div>
          </div>

          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Active Sessions</span>
              <ShieldCheck className="h-4 w-4" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {activeSessions.length}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400">
              Across browsers & mobile devices
            </div>
          </div>

          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Editorial Activity</span>
              <History className="h-4 w-4" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {recentContentLogs.length}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400">
              Logged editorial operations
            </div>
          </div>
        </div>
      ) : (
        /* Sub-Admin Role Card */
        <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div>
              <div className="flex items-center gap-2">
                <Sparkles className="h-5 w-5 text-neutral-700 dark:text-neutral-300" />
                <h2 className="font-bold text-base text-neutral-900 dark:text-white">
                  Welcome to your Editorial Workspace
                </h2>
              </div>
              <p className="mt-1 max-w-2xl text-xs text-neutral-500">
                You are logged in with the <strong>{(user.role || "SUB_ADMIN").replace(/_/g, " ")}</strong> role. Your
                permissions are bounded to authorized editorial operations. Administrative settings
                and security controls are managed by the Main Administrator.
              </p>
            </div>
            <div className="flex items-center gap-2">
              <Link
                href="/admin/activity"
                className="flex h-8 items-center gap-1.5 rounded-lg border border-neutral-200 px-3 text-xs font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800"
              >
                <span>View Content Logs</span>
                <ArrowRight className="h-3 w-3" />
              </Link>
            </div>
          </div>

          <div className="mt-6 border-t border-neutral-100 pt-4 dark:border-neutral-800">
            <span className="text-[10px] font-bold tracking-wider text-neutral-400 uppercase">
              Assigned Permissions:
            </span>
            <div className="mt-2 flex flex-wrap gap-2">
              {permissions.map((p) => (
                <span
                  key={p}
                  className="rounded-md border border-neutral-200 bg-neutral-50 px-2 py-1 text-[11px] font-mono text-neutral-700 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-300"
                >
                  {p}
                </span>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* CMS Publishing Intelligence (Live MongoDB Atlas data) */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <FileText className="h-4 w-4 text-neutral-900 dark:text-white" />
            <h2 className="font-bold text-base text-neutral-900 dark:text-white">
              Blog CMS & Editorial Publishing
            </h2>
          </div>
          <div className="flex items-center gap-2">
            <Link
              href="/admin/posts/new"
              className="flex h-8 items-center gap-1.5 rounded-lg bg-neutral-900 px-3 text-xs font-semibold text-white hover:bg-neutral-800 dark:bg-white dark:text-neutral-900"
            >
              <Plus className="h-3.5 w-3.5" />
              <span>Create Article</span>
            </Link>
            <Link
              href="/blog"
              target="_blank"
              className="flex h-8 items-center gap-1.5 rounded-lg border border-neutral-200 px-3 text-xs font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <ExternalLink className="h-3.5 w-3.5" />
              <span>View Public Blog</span>
            </Link>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Link
            href="/admin/posts?status=PUBLISHED"
            className="group rounded-xl border border-neutral-200 bg-white p-5 shadow-xs transition hover:border-neutral-400 dark:border-neutral-800 dark:bg-neutral-900 dark:hover:border-neutral-600"
          >
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Published Articles</span>
              <span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {publishedCount}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400 group-hover:text-neutral-600 dark:group-hover:text-neutral-300">
              Live on /blog & sitemap &rarr;
            </div>
          </Link>

          <Link
            href="/admin/posts?status=SCHEDULED"
            className="group rounded-xl border border-neutral-200 bg-white p-5 shadow-xs transition hover:border-neutral-400 dark:border-neutral-800 dark:bg-neutral-900 dark:hover:border-neutral-600"
          >
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Scheduled Releases</span>
              <Clock className="h-4 w-4 text-amber-500" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {scheduledCount}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400 group-hover:text-neutral-600 dark:group-hover:text-neutral-300">
              Serverless cron publishing &rarr;
            </div>
          </Link>

          <Link
            href="/admin/posts?status=DRAFT"
            className="group rounded-xl border border-neutral-200 bg-white p-5 shadow-xs transition hover:border-neutral-400 dark:border-neutral-800 dark:bg-neutral-900 dark:hover:border-neutral-600"
          >
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Active Drafts</span>
              <FileText className="h-4 w-4 text-blue-500" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {draftCount}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400 group-hover:text-neutral-600 dark:group-hover:text-neutral-300">
              In editorial studio &rarr;
            </div>
          </Link>

          <Link
            href="/admin/media"
            className="group rounded-xl border border-neutral-200 bg-white p-5 shadow-xs transition hover:border-neutral-400 dark:border-neutral-800 dark:bg-neutral-900 dark:hover:border-neutral-600"
          >
            <div className="flex items-center justify-between text-neutral-500">
              <span className="text-xs font-semibold">Media Assets</span>
              <ImageIcon className="h-4 w-4 text-purple-500" />
            </div>
            <div className="mt-3 font-bold text-2xl text-neutral-900 dark:text-white">
              {mediaCount}
            </div>
            <div className="mt-1 text-[11px] text-neutral-400 group-hover:text-neutral-600 dark:group-hover:text-neutral-300">
              WebP / PNG / JPEG library &rarr;
            </div>
          </Link>
        </div>
      </div>

      {/* Main Admin: Security Audit Feed + Content Activity Feed */}
      {isMainAdmin ? (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          {/* Security Audit Feed */}
          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <ShieldAlert className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Security Audit (Main Admin Only)
                </h3>
              </div>
              <Link
                href="/admin/security/audit"
                className="text-xs font-medium text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
              >
                View full audit &rarr;
              </Link>
            </div>

            <div className="mt-4 space-y-3">
              {recentSecurityLogs.length === 0 ? (
                <p className="py-4 text-center text-xs text-neutral-400">
                  No security events recorded yet.
                </p>
              ) : (
                recentSecurityLogs.map((log) => (
                  <div
                    key={log.id}
                    className="flex items-start justify-between rounded-lg border border-neutral-100 bg-neutral-50/50 p-3 text-xs dark:border-neutral-800/50 dark:bg-neutral-950/50"
                  >
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-semibold text-neutral-900 dark:text-white">
                          {(log.action || "").replace(/_/g, " ")}
                        </span>
                        <span className="text-[10px] text-neutral-400">by {log.actorName}</span>
                      </div>
                      {log.targetUserName && (
                        <div className="mt-0.5 text-[11px] text-neutral-500">
                          Target: {log.targetUserName} ({log.targetUserEmail})
                        </div>
                      )}
                    </div>
                    <span suppressHydrationWarning className="text-[10px] text-neutral-400">
                      {new Date(log.timestamp).toLocaleTimeString("en-US", {
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Content Activity Feed */}
          <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <FileText className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Recent Content Activity
                </h3>
              </div>
              <Link
                href="/admin/activity"
                className="text-xs font-medium text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
              >
                View all activity &rarr;
              </Link>
            </div>

            <div className="mt-4 space-y-3">
              {recentContentLogs.length === 0 ? (
                <p className="py-4 text-center text-xs text-neutral-400">
                  No editorial activity recorded yet.
                </p>
              ) : (
                recentContentLogs.map((log) => (
                  <div
                    key={log.id}
                    className="flex items-start justify-between rounded-lg border border-neutral-100 bg-neutral-50/50 p-3 text-xs dark:border-neutral-800/50 dark:bg-neutral-950/50"
                  >
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-semibold text-neutral-900 dark:text-white">
                          {(log.action || "").replace(/_/g, " ")}
                        </span>
                        <span className="text-[10px] text-neutral-400">by {log.actorName}</span>
                      </div>
                      {log.postTitle && (
                        <div className="mt-0.5 text-[11px] text-neutral-500">
                          Post: &ldquo;{log.postTitle}&rdquo;
                        </div>
                      )}
                    </div>
                    <span suppressHydrationWarning className="text-[10px] text-neutral-400">
                      {new Date(log.timestamp).toLocaleDateString("en-US", {
                        month: "short",
                        day: "numeric",
                      })}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      ) : (
        /* Sub-Admin Content Feed */
        <div className="rounded-xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
          <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
            <div className="flex items-center gap-2">
              <FileText className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
              <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                Recent Editorial Actions
              </h3>
            </div>
            <Link
              href="/admin/activity"
              className="text-xs font-medium text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
            >
              Full history &rarr;
            </Link>
          </div>

          <div className="mt-4 space-y-3">
            {recentContentLogs.length === 0 ? (
              <p className="py-4 text-center text-xs text-neutral-400">
                No recent editorial actions found.
              </p>
            ) : (
              recentContentLogs.map((log) => (
                <div
                  key={log.id}
                  className="flex items-start justify-between rounded-lg border border-neutral-100 bg-neutral-50/50 p-3 text-xs dark:border-neutral-800/50 dark:bg-neutral-950/50"
                >
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-semibold text-neutral-900 dark:text-white">
                        {(log.action || "").replace(/_/g, " ")}
                      </span>
                      <span className="text-[10px] text-neutral-400">by {log.actorName}</span>
                    </div>
                    {log.postTitle && (
                      <div className="mt-0.5 text-[11px] text-neutral-500">
                        Post: &ldquo;{log.postTitle}&rdquo;
                      </div>
                    )}
                  </div>
                  <span suppressHydrationWarning className="text-[10px] text-neutral-400">
                    {new Date(log.timestamp).toLocaleDateString("en-US", {
                      month: "short",
                      day: "numeric",
                    })}
                  </span>
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
