import {
  Blocks,
  Globe,
  History,
  KeyRound,
  LayoutDashboard,
  ScrollText,
  ShieldCheck,
  UserCog,
  Users,
} from "lucide-react";
import Link from "next/link";

import { ListPageCard } from "@/app/dashboard/_components";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Button } from "@/components/ui/button";
import { fetchBackendAuditLog } from "@/app/dashboard/admins/access/audit/_lib/audit-server-api";
import { fetchBackendRoles } from "@/app/dashboard/admins/access/roles/_lib/roles-server-api";
import { fetchBackendUsers } from "@/app/dashboard/admins/users/_lib/users-server-api";
import { fetchBackendCustomers } from "@/app/dashboard/customers/_lib/customers-list-api";

export default async function AdminsOverviewPage() {
  const [usersResult, rolesResult, auditResult, customersResult] = await Promise.all([
    fetchBackendUsers(),
    fetchBackendRoles(),
    fetchBackendAuditLog({ pageSize: 5 }),
    fetchBackendCustomers({ page: 1, pageSize: 1 }),
  ]);

  const criticalErrors = [usersResult.errorMessage, customersResult.errorMessage].filter(Boolean);
  const errorMessage = criticalErrors[0] ?? null;
  const auditUnavailable = !auditResult.available;

  const quickLinks = [
  {
    title: "Staff Users",
    description: "Backend operator accounts",
    href: "/dashboard/admins/users",
    icon: Users,
  },
  {
    title: "Roles",
    description: "RBAC role templates and custom roles",
    href: "/dashboard/admins/access/roles",
    icon: ShieldCheck,
  },
  {
    title: "Permissions",
    description: "Permission catalog",
    href: "/dashboard/admins/access/permissions",
    icon: KeyRound,
  },
  {
    title: "App Modules",
    description: "Module groupings for permissions",
    href: "/dashboard/admins/access/app-modules",
    icon: Blocks,
  },
  {
    title: "Portal ACL",
    description: "Customer portal apps, roles, and users",
    href: "/dashboard/admins/portal/entitlements",
    icon: Globe,
  },
  {
    title: "Audit Log",
    description: "RBAC and portal change history",
    href: "/dashboard/admins/access/audit",
    icon: ScrollText,
  },
];

  return (
    <ListPageCard
      icon={UserCog}
      title="Admins & Access"
      description="Manage staff RBAC, customer portal ACL, and audit history from one hub."
      breadcrumb={[{ label: "Admins & Access" }]}
    >
      <ErrorBanner message={errorMessage} className="mb-4" />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Staff users" value={usersResult.total || usersResult.users.length} />
        <StatCard label="Roles" value={rolesResult.roles.length} />
        <StatCard label="Customers" value={customersResult.totalCount} />
        <StatCard label="Recent audit events" value={auditResult.entries.length} />
      </div>

      <div className="mt-6 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {quickLinks.map((link) => (
          <Link
            key={link.href}
            href={link.href}
            className="group rounded-2xl border bg-card p-4 shadow-sm transition-colors hover:border-primary/30 hover:bg-muted/30"
          >
            <div className="flex items-start gap-3">
              <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
                <link.icon className="size-5" />
              </div>
              <div className="min-w-0">
                <p className="font-medium">{link.title}</p>
                <p className="mt-1 text-muted-foreground text-sm">{link.description}</p>
              </div>
            </div>
          </Link>
        ))}
      </div>

      <div className="mt-6 rounded-2xl border bg-card p-4 shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="font-semibold text-base">Recent audit activity</h2>
            <p className="text-muted-foreground text-sm">Latest RBAC and portal access changes.</p>
          </div>
          <Button asChild variant="outline" size="sm">
            <Link href="/dashboard/admins/access/audit">
              <History className="size-4" />
              View all
            </Link>
          </Button>
        </div>
        {auditUnavailable ? (
          <p className="mt-4 text-muted-foreground text-sm">
            Audit log is not available yet. RBAC changes will appear here once the backend audit API is enabled.
          </p>
        ) : auditResult.entries.length === 0 ? (
          <p className="mt-4 text-muted-foreground text-sm">No audit entries yet.</p>
        ) : (
          <ul className="mt-4 space-y-2">
            {auditResult.entries.map((entry) => (
              <li
                key={entry.id}
                className="flex flex-wrap items-center justify-between gap-2 rounded-xl border bg-muted/20 px-3 py-2 text-sm"
              >
                <span>
                  <span className="font-medium">{entry.actorDisplayName}</span>
                  <span className="text-muted-foreground"> · {entry.action}</span>
                  <span className="font-mono"> {entry.itemName}</span>
                </span>
                <span className="text-muted-foreground text-xs">{entry.timestamp}</span>
              </li>
            ))}
          </ul>
        )}
      </div>
    </ListPageCard>
  );
}

function StatCard({ label, value }: { label: string; value: number }) {
  return (
    <div className="rounded-2xl border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between gap-2">
        <p className="text-muted-foreground text-sm">{label}</p>
        <LayoutDashboard className="size-4 text-primary" />
      </div>
      <p className="mt-2 font-semibold text-3xl tracking-tight">{value}</p>
    </div>
  );
}
