import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import { getSetting } from "@/lib/settings";
import {
  LayoutDashboard,
  Video,
  FolderTree,
  CreditCard,
  ShoppingBag,
  MessageSquare,
  HeartHandshake,
  BarChart3,
  Users,
  Settings,
  Mail,
  Star,
  Clock,
  Target,
  Sparkles,
  Trash2,
  Landmark,
  Repeat,
  ExternalLink,
} from "lucide-react";

export const dynamic = "force-dynamic";

const ALL_SECTIONS = [
  { key: "dashboard", href: "/admin", label: "Dashboard", icon: LayoutDashboard, group: null },

  { key: "videos", href: "/admin/videos", label: "Videos", icon: Video, group: "Content" },
  { key: "categories", href: "/admin/categories", label: "Categories", icon: FolderTree, group: "Content" },
  { key: "plans", href: "/admin/plans", label: "Membership Plans", icon: CreditCard, group: "Content" },
  { key: "products", href: "/admin/products", label: "Shop Products", icon: ShoppingBag, group: "Content" },

  { key: "posts", href: "/admin/posts", label: "Community Posts", icon: MessageSquare, group: "Community" },
  { key: "deleted-posts", href: "/admin/deleted-posts", label: "Deleted Posts", icon: Trash2, group: "Community" },
  { key: "missions", href: "/admin/missions", label: "Missions & Targets", icon: Target, group: "Community" },
  { key: "points", href: "/admin/points", label: "Points System", icon: Star, group: "Community" },
  { key: "users", href: "/admin/users", label: "Users & Roles", icon: Users, group: "Community" },

  { key: "funding", href: "/admin/funding", label: "Funding Dashboard", icon: HeartHandshake, group: "Finance" },
  { key: "reports", href: "/admin/reports", label: "Strong Reports", icon: BarChart3, group: "Finance" },
  { key: "recurring", href: "/admin/recurring", label: "Recurring Revenue", icon: Repeat, group: "Finance" },
  { key: "accounting", href: "/admin/accounting", label: "Accounting", icon: Landmark, group: "Finance" },
  { key: "supporters", href: "/admin/supporters", label: "Supporters", icon: HeartHandshake, group: "Finance" },
  { key: "test-billing", href: "/admin/test-billing", label: "Test Recurring Billing", icon: Clock, group: "Finance" },

  { key: "emails", href: "/admin/emails", label: "Email Templates", icon: Mail, group: "Marketing" },
  { key: "email-campaign", href: "/admin/email-campaign", label: "Email Campaign", icon: Mail, group: "Marketing" },
  { key: "welcome-animation", href: "/admin/welcome-animation", label: "Welcome Animation", icon: Sparkles, group: "Marketing" },

  { key: "analytics", href: "/admin/analytics", label: "Visitor Analytics", icon: BarChart3, group: "Site" },
  { key: "settings", href: "/admin/settings", label: "Site Settings", icon: Settings, group: "Site" },
];

const GROUP_ORDER = ["Content", "Community", "Finance", "Marketing", "Site"];

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  const session = await auth();
  if (!session?.user || (session.user as any).role !== "admin") {
    redirect("/admin-login");
  }

  const siteName = await getSetting("siteName", "GraceMembership");

  let permissions: string[] | null = null;
  try {
    const raw = (session.user as any).permissions;
    if (raw) permissions = JSON.parse(raw);
  } catch {
    permissions = null;
  }

  const links = permissions ? ALL_SECTIONS.filter((s) => permissions!.includes(s.key)) : ALL_SECTIONS;

  return (
    <div className="min-h-screen flex" style={{ background: "#0a0a0a", color: "#f5f5f5" }}>
      <aside className="hidden md:flex md:flex-col w-60 shrink-0 border-r border-neutral-800 bg-[#0f0f0f] p-4 sticky top-0 h-screen overflow-y-auto">
        <div className="flex items-center gap-2 mb-1 px-1">
          <span className="w-8 h-8 rounded-lg bg-red-600 flex items-center justify-center font-bold text-sm">A</span>
          <div>
            <p className="font-bold text-sm leading-tight">{siteName}</p>
            <p className="text-xs text-neutral-500 leading-tight">Admin Panel</p>
          </div>
        </div>
        <nav className="space-y-1 text-sm mt-6">
          {links.filter((l) => !l.group).map((l) => {
            const Icon = l.icon;
            return (
              <Link key={l.href} href={l.href} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-neutral-300 hover:bg-neutral-800 hover:text-white transition-colors">
                <Icon size={17} />
                {l.label}
              </Link>
            );
          })}

          {GROUP_ORDER.map((groupName) => {
            const groupLinks = links.filter((l) => l.group === groupName);
            if (groupLinks.length === 0) return null;
            return (
              <div key={groupName} className="pt-4">
                <p className="px-3 text-[10px] font-bold uppercase tracking-wider text-neutral-600 mb-1">{groupName}</p>
                {groupLinks.map((l) => {
                  const Icon = l.icon;
                  return (
                    <Link key={l.href} href={l.href} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-neutral-300 hover:bg-neutral-800 hover:text-white transition-colors">
                      <Icon size={17} />
                      {l.label}
                    </Link>
                  );
                })}
              </div>
            );
          })}
        </nav>
        <a
          href="/"
          target="_blank"
          rel="noopener noreferrer"
          className="mt-auto flex items-center gap-2 text-sm text-neutral-400 hover:text-white px-3 py-2.5 rounded-lg hover:bg-neutral-800"
        >
          <ExternalLink size={16} /> View Live Site
        </a>
      </aside>

      <div className="flex-1 min-w-0">
        <header className="md:hidden border-b border-neutral-800 bg-[#0f0f0f] px-4 py-3 flex items-center justify-between">
          <span className="font-bold">{siteName} Admin</span>
          <a href="/" target="_blank" rel="noopener noreferrer" className="text-red-500 text-sm">View Site →</a>
        </header>
        <main className="p-4 md:p-8 max-w-7xl mx-auto">{children}</main>
      </div>
    </div>
  );
}
