import { Link, useRouterState } from "@tanstack/react-router";
import { useT, type Lang } from "@/lib/i18n";
import { useTheme } from "@/lib/theme";
import { supabase } from "@/integrations/supabase/client";
import { useRouter } from "@tanstack/react-router";
import {
  LayoutDashboard, Package, ShoppingCart, ListOrdered, TrendingUp, Users, Truck,
  Tags, Layers, Wallet, BarChart3, LogOut, Store, Sun, Moon, Languages, Menu, X,
  UserCog, ShieldAlert, AlertTriangle, CalendarDays, PiggyBank,
} from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useRole, canAccess, type AppRole } from "@/lib/use-role";
import { AIAssistant } from "@/components/ai-assistant";

type NavItem = { to: string; label: string; icon: any; exact?: boolean; roles?: AppRole[] };
type NavGroup = { label: string; items: NavItem[]; roles?: AppRole[] };

const navGroups = (t: any): NavGroup[] => [
  {
    label: t("dashboard"),
    items: [
      { to: "/", label: t("dashboard"), icon: LayoutDashboard, exact: true },
    ],
  },
  {
    label: t("sales"),
    items: [
      { to: "/pos", label: t("pos"), icon: ShoppingCart },
      { to: "/sales", label: t("sales"), icon: ListOrdered },
      { to: "/customers", label: t("customers"), icon: Users },
    ],
  },
  {
    label: t("products"),
    items: [
      { to: "/products", label: t("products"), icon: Package },
      { to: "/damaged", label: t("damaged"), icon: AlertTriangle, roles: ["super_admin"] },
      { to: "/categories", label: t("categories"), icon: Tags, roles: ["super_admin"] },
      { to: "/brands", label: t("brands"), icon: Layers, roles: ["super_admin"] },
    ],
  },
  {
    label: t("purchases"),
    roles: ["super_admin"],
    items: [
      { to: "/purchases", label: t("purchases"), icon: TrendingUp, roles: ["super_admin"] },
      { to: "/suppliers", label: t("suppliers"), icon: Truck, roles: ["super_admin"] },
    ],
  },
  {
    label: t("reports"),
    roles: ["super_admin"],
    items: [
      { to: "/daily-report", label: t("daily_report"), icon: CalendarDays, roles: ["super_admin"] },
      { to: "/expenses", label: t("expenses"), icon: Wallet, roles: ["super_admin"] },
      { to: "/investments", label: t("investments"), icon: PiggyBank, roles: ["super_admin"] },
      { to: "/reports", label: t("reports"), icon: BarChart3, roles: ["super_admin"] },
    ],
  },
  {
    label: t("settings"),
    roles: ["super_admin"],
    items: [
      { to: "/users", label: t("users"), icon: UserCog, roles: ["super_admin"] },
    ],
  },
];

function filterGroups(groups: NavGroup[], role: AppRole | null): NavGroup[] {
  if (!role) return [];
  return groups
    .filter((g) => !g.roles || g.roles.includes(role))
    .map((g) => ({ ...g, items: g.items.filter((it) => !it.roles || it.roles.includes(role)) }))
    .filter((g) => g.items.length > 0);
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const { t, lang, setLang } = useT();
  const { theme, toggle } = useTheme();
  const router = useRouter();
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const [mobileOpen, setMobileOpen] = useState(false);
  const { role, loading: roleLoading } = useRole();
  const groups = filterGroups(navGroups(t), role);
  const allowed = roleLoading || canAccess(role, pathname);

  const handleLogout = async () => {
    await supabase.auth.signOut();
    router.navigate({ to: "/auth" });
  };

  return (
    <div className="min-h-screen flex bg-muted/40">
      {/* Sidebar — desktop */}
      <aside className="hidden lg:flex w-64 flex-col gradient-sidebar text-sidebar-foreground sticky top-0 h-screen">
        <SidebarBranding />
        <nav className="flex-1 overflow-y-auto px-3 py-2 space-y-4">
          {groups.map((g) => (
            <div key={g.label}>
              <div className="text-[11px] uppercase tracking-wider text-sidebar-foreground/40 px-3 mb-1 font-semibold">{g.label}</div>
              <div className="space-y-0.5">
                {g.items.map((it) => {
                  const active = it.exact ? pathname === it.to : pathname.startsWith(it.to);
                  return (
                    <Link
                      key={it.to}
                      to={it.to as any}
                      onClick={() => setMobileOpen(false)}
                      className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all ${
                        active
                          ? "bg-sidebar-primary text-sidebar-primary-foreground shadow-glow font-semibold"
                          : "text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-foreground"
                      }`}
                    >
                      <it.icon className="size-4 shrink-0" />
                      <span className="truncate">{it.label}</span>
                    </Link>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>
        <div className="p-3 border-t border-sidebar-border">
          <button onClick={handleLogout} className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-sidebar-foreground/70 hover:bg-destructive/20 hover:text-destructive-foreground transition">
            <LogOut className="size-4" /> {t("logout")}
          </button>
        </div>
      </aside>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-black/60" onClick={() => setMobileOpen(false)} />
          <aside className="absolute left-0 top-0 bottom-0 w-72 gradient-sidebar text-sidebar-foreground flex flex-col animate-fade-in">
            <SidebarBranding onClose={() => setMobileOpen(false)} />
            <nav className="flex-1 overflow-y-auto px-3 py-2 space-y-4">
              {groups.map((g) => (
                <div key={g.label}>
                  <div className="text-[11px] uppercase tracking-wider text-sidebar-foreground/40 px-3 mb-1 font-semibold">{g.label}</div>
                  {g.items.map((it) => {
                    const active = it.exact ? pathname === it.to : pathname.startsWith(it.to);
                    return (
                      <Link key={it.to} to={it.to as any} onClick={() => setMobileOpen(false)}
                        className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm ${active ? "bg-sidebar-primary text-sidebar-primary-foreground" : "hover:bg-sidebar-accent"}`}>
                        <it.icon className="size-4" /> {it.label}
                      </Link>
                    );
                  })}
                </div>
              ))}
            </nav>
          </aside>
        </div>
      )}

      <div className="flex-1 flex flex-col min-w-0">
        {/* Topbar */}
        <header className="sticky top-0 z-30 glass border-b">
          <div className="flex items-center justify-between px-4 lg:px-6 h-16">
            <div className="flex items-center gap-3">
              <Button size="icon" variant="ghost" className="lg:hidden" onClick={() => setMobileOpen(true)}>
                <Menu className="size-5" />
              </Button>
              <div className="lg:hidden flex items-center gap-2">
                <div className="size-8 rounded-lg gradient-primary grid place-items-center text-white"><Store className="size-4" /></div>
                <span className="font-bold">{t("app_name")}</span>
              </div>
            </div>
            <div className="flex items-center gap-1">
              <Button size="icon" variant="ghost" onClick={() => setLang((lang === "bn" ? "en" : "bn") as Lang)} title="Language">
                <Languages className="size-4" />
                <span className="ml-1 text-xs font-bold">{lang === "bn" ? "EN" : "বাং"}</span>
              </Button>
              <Button size="icon" variant="ghost" onClick={toggle} title="Theme">
                {theme === "dark" ? <Sun className="size-4" /> : <Moon className="size-4" />}
              </Button>
            </div>
          </div>
        </header>

        <main className="flex-1 p-4 md:p-6 lg:p-8 pb-24 lg:pb-8 animate-fade-in overflow-x-hidden">
          {allowed ? children : (
            <div className="max-w-md mx-auto mt-20 text-center space-y-3">
              <div className="size-16 rounded-2xl bg-destructive/10 grid place-items-center mx-auto">
                <ShieldAlert className="size-8 text-destructive" />
              </div>
              <h2 className="text-xl font-bold">{t("no_permission")}</h2>
              <p className="text-sm text-muted-foreground">{t("no_permission_desc")}</p>
              <Button onClick={() => router.navigate({ to: "/" })}>{t("dashboard")}</Button>
            </div>
          )}
        </main>

        <Footer />

        {/* Mobile bottom nav */}
        <nav className="lg:hidden fixed bottom-0 inset-x-0 z-40 glass border-t flex justify-around py-2">
          {([
            { to: "/", icon: LayoutDashboard, label: t("dashboard"), exact: true },
            { to: "/pos", icon: ShoppingCart, label: t("pos") },
            { to: "/products", icon: Package, label: t("products") },
            ...(role === "super_admin"
              ? [{ to: "/reports", icon: BarChart3, label: t("reports") }]
              : [{ to: "/sales", icon: ListOrdered, label: t("sales") }]),
          ] as any[]).map((it) => {
            const active = it.exact ? pathname === it.to : pathname.startsWith(it.to);
            return (
              <Link key={it.to} to={it.to as any} className={`flex flex-col items-center gap-0.5 text-[10px] p-1.5 rounded-lg min-w-16 ${active ? "text-primary font-bold" : "text-muted-foreground"}`}>
                <it.icon className="size-5" />
                <span className="truncate">{it.label}</span>
              </Link>
            );
          })}
        </nav>
      </div>
      <AIAssistant />
    </div>
  );
}

function SidebarBranding({ onClose }: { onClose?: () => void }) {
  const { t } = useT();
  return (
    <div className="px-5 py-5 border-b border-sidebar-border flex items-center justify-between">
      <div className="flex items-center gap-3 min-w-0">
        <div className="size-10 rounded-xl gradient-primary grid place-items-center shadow-glow shrink-0">
          <Store className="size-5 text-white" />
        </div>
        <div className="min-w-0">
          <div className="font-extrabold text-base truncate">{t("app_name")}</div>
          <div className="text-[10px] text-sidebar-foreground/50 truncate">Premium POS & Inventory</div>
        </div>
      </div>
      {onClose && (
        <button onClick={onClose} className="lg:hidden text-sidebar-foreground/60"><X className="size-5" /></button>
      )}
    </div>
  );
}

export function Footer() {
  return (
    <footer className="border-t bg-card mt-auto no-print">
      <div className="px-4 md:px-6 lg:px-8 py-4 flex flex-col md:flex-row items-center justify-between gap-2 text-xs text-muted-foreground">
        <div>
          Developed by{" "}
          <span className="font-bold text-primary">Md Waliduzzaman Sarder</span>
        </div>
        <div className="flex items-center gap-4">
          <span className="hover:text-foreground">Helpgate Inventory</span>
          <a href="tel:01722427373" className="hover:text-foreground font-medium">📞 Hotline: 01722427373</a>
        </div>
      </div>
    </footer>
  );
}
