"use client";

import { useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import GlobalAutoSync from "./GlobalAutoSync";
import NavigationProgress from "./NavigationProgress";
import Sidebar, { type NavigationGroup } from "./Sidebar";
import Topbar from "./Topbar";
import { CurrentUserProvider, type CurrentUser } from "./CurrentUserContext";

const publicPaths = ["/login", "/product-brief", "/console-setup"];

export default function AppShell({ children, currentUser }: { children: React.ReactNode; currentUser: CurrentUser }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [menuOpen, setMenuOpen] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const shopId = searchParams.get("shop_id") || "all";
  const isSuperAdmin = currentUser?.role === "super_admin";
  const adminMode = isSuperAdmin && (pathname === "/admin" || pathname === "/users" || (shopId === "all" && ["/tokens", "/logs", "/settings"].includes(pathname)));
  const scoped = (href: string) => `${href}?shop_id=${encodeURIComponent(shopId)}`;
  const canManageUsers = currentUser?.role === "super_admin" || currentUser?.role === "owner";
  const canAccessAi = currentUser?.role === "super_admin" || currentUser?.role === "owner";

  const workspaceNavigation: NavigationGroup[] = [
    {
      label: "Operasional",
      items: [
        ...(isSuperAdmin ? [{ label: "Kembali ke Super Admin", href: "/admin", icon: "users" as const }] : []),
        { label: "Ringkasan", href: scoped("/dashboard"), icon: "dashboard" },
        { label: "Pesanan", href: scoped("/orders"), icon: "orders" },
        { label: "Produk", href: scoped("/products"), icon: "products" },
      ],
    },
    {
      label: "Keuangan",
      collapsible: true,
      items: [
        { label: "Profit", href: scoped("/finance"), icon: "finance" },
        { label: "Laporan", href: scoped("/reports"), icon: "reports" },
      ],
    },
    ...(canAccessAi
      ? [
          {
            label: "AI Agent",
            collapsible: true,
            items: [
              { label: "AI Agent Profit", href: scoped("/optimizer"), icon: "optimizer" as const },
            ],
          },
        ]
      : []),
    {
      label: "Sistem",
      collapsible: true,
      items: [
        { label: "Toko & Koneksi", href: scoped("/tokens"), icon: "stores" },
        { label: "Aktivitas Sistem", href: scoped("/logs"), icon: "logs" },
        ...(canManageUsers
          ? [{ label: "Manajemen Pengguna", href: scoped("/users"), icon: "users" as const }]
          : []),
        { label: canAccessAi ? "Pengaturan & AI" : "Pengaturan Akun", href: scoped("/settings"), icon: "settings" },
      ],
    },
  ];
  const navigation: NavigationGroup[] = adminMode ? [
    { label: "Administrasi", items: [{ label: "Pusat Super Admin", href: "/admin", icon: "dashboard" }] },
    { label: "Sistem", collapsible: true, items: [
      { label: "Toko & Koneksi", href: "/tokens?shop_id=all", icon: "stores" },
      { label: "Aktivitas Sistem", href: "/logs?shop_id=all", icon: "logs" },
      { label: "Manajemen Pengguna", href: "/users?shop_id=all", icon: "users" },
      { label: "Pengaturan & AI", href: "/settings?shop_id=all", icon: "settings" },
    ] },
  ] : workspaceNavigation;

  if (publicPaths.includes(pathname)) return <CurrentUserProvider user={currentUser}><main className="min-h-dvh bg-slate-100 dark:bg-slate-950">{children}</main></CurrentUserProvider>;

  return (
    <CurrentUserProvider user={currentUser}><div className="sellfin-app min-h-dvh bg-[#f5f6f8] text-slate-950 dark:bg-slate-950 dark:text-slate-100 lg:flex">
      <GlobalAutoSync />
      <NavigationProgress />
      <Sidebar groups={navigation} open={menuOpen} collapsed={sidebarCollapsed} mode={adminMode ? "admin" : "workspace"} onClose={() => setMenuOpen(false)} onToggle={() => setSidebarCollapsed((value) => !value)} />
      <div className="flex min-h-dvh min-w-0 flex-1 flex-col overflow-x-hidden">
        <Topbar onMenu={() => setMenuOpen(true)} />
        <main className="mx-auto w-full max-w-[1680px] min-w-0 flex-1 space-y-5 px-4 py-6 sm:px-6 xl:px-8">{children}</main>
      </div>
    </div></CurrentUserProvider>
  );
}
