import { Link, useRouterState, useNavigate } from "@tanstack/react-router";
import type { ReactNode } from "react";
import {
  Crown,
  LayoutDashboard,
  Users,
  KeyRound,
  Gamepad2,
  ArrowLeftRight,
  LifeBuoy,
  Mail,
  Settings,
  LogOut,
  ChevronLeft,
  Wallet,
  Coins,
  Send,
  Shield,
  Globe,
  UserCog,
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useState } from "react";

type Item = { to: string; label: string; icon: React.ComponentType<{ className?: string }>; group?: string };

const adminNav: Item[] = [
  { to: "/admin/dashboard", label: "Dashboard", icon: LayoutDashboard, group: "Overview" },
  { to: "/admin/clients", label: "Client Management", icon: Users, group: "Operations" },
  { to: "/admin/wallets", label: "Wallet Management", icon: Wallet, group: "Operations" },
  { to: "/admin/transactions", label: "Transactions", icon: ArrowLeftRight, group: "Operations" },
  { to: "/admin/api-keys", label: "API Configuration", icon: KeyRound, group: "Operations" },
  { to: "/admin/providers", label: "Game Providers", icon: Gamepad2, group: "Catalog" },
  { to: "/admin/currencies", label: "Multi-Currency", icon: Coins, group: "Catalog" },
  { to: "/admin/tickets", label: "Support Tickets", icon: LifeBuoy, group: "Support" },
  { to: "/admin/contacts", label: "Contact Inbox", icon: Mail, group: "Support" },
  { to: "/admin/telegram", label: "Telegram", icon: Send, group: "Settings" },
  { to: "/admin/roles", label: "Role Management", icon: UserCog, group: "Settings" },
  { to: "/admin/website", label: "Website Settings", icon: Globe, group: "Settings" },
  { to: "/admin/security", label: "Security", icon: Shield, group: "Settings" },
  { to: "/admin/settings", label: "All Settings", icon: Settings, group: "Settings" },
];

const clientNav: Item[] = [
  { to: "/client/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { to: "/client/api-keys", label: "API Keys", icon: KeyRound },
  { to: "/client/transactions", label: "Transactions", icon: ArrowLeftRight },
  { to: "/client/games", label: "Game List", icon: Gamepad2 },
  { to: "/client/support", label: "Support", icon: LifeBuoy },
];

export function PanelShell({
  kind,
  title,
  children,
  user,
}: {
  kind: "admin" | "client";
  title: string;
  children: ReactNode;
  user?: { email?: string; displayName?: string };
}) {
  const nav = kind === "admin" ? adminNav : clientNav;
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);

  async function signOut() {
    await supabase.auth.signOut();
    navigate({ to: "/auth", replace: true });
  }

  return (
    <div className="min-h-screen flex bg-background">
      {/* Sidebar */}
      <aside
        className={`${
          open ? "translate-x-0" : "-translate-x-full"
        } lg:translate-x-0 fixed lg:static z-40 inset-y-0 left-0 w-64 border-r border-border bg-surface/70 backdrop-blur-xl flex flex-col transition-transform`}
      >
        <div className="h-16 px-5 flex items-center gap-2.5 border-b border-border">
          <div
            className="h-9 w-9 rounded-lg grid place-items-center"
            style={{ background: "var(--gradient-gold)" }}
          >
            <Crown className="h-5 w-5" style={{ color: "oklch(0.13 0.018 280)" }} />
          </div>
          <div className="leading-tight">
            <div className="font-display text-[13px] font-bold text-gradient">CASINO API</div>
            <div className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground -mt-0.5">
              {kind === "admin" ? "Admin panel" : "Client portal"}
            </div>
          </div>
        </div>

        <nav className="flex-1 px-2 py-2 space-y-2 overflow-y-auto">
          {Object.entries(
            nav.reduce<Record<string, Item[]>>((acc, item) => {
              const g = item.group ?? "Menu";
              (acc[g] ??= []).push(item);
              return acc;
            }, {}),
          ).map(([group, items]) => (
            <div key={group}>
              <div className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-[0.18em] text-muted-foreground/70">
                {group}
              </div>
              <div className="space-y-0.5">
                {items.map((item) => {
                  const active = pathname === item.to || pathname.startsWith(item.to + "/");
                  return (
                    <Link
                      key={item.to}
                      to={item.to}
                      className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition ${
                        active
                          ? "bg-primary/15 text-gold border border-primary/30"
                          : "text-muted-foreground hover:text-foreground hover:bg-surface-2/60"
                      }`}
                    >
                      <item.icon className="h-4 w-4" />
                      {item.label}
                    </Link>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>


        <div className="p-3 border-t border-border">
          <div className="px-2 py-2 flex items-center gap-3">
            <div
              className="h-9 w-9 rounded-full grid place-items-center text-xs font-bold"
              style={{ background: "var(--gradient-gold)", color: "oklch(0.13 0.018 280)" }}
            >
              {(user?.displayName ?? user?.email ?? "?").slice(0, 2).toUpperCase()}
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium truncate">{user?.displayName ?? "User"}</div>
              <div className="text-[11px] text-muted-foreground truncate">{user?.email}</div>
            </div>
          </div>
          <button
            onClick={signOut}
            className="mt-2 w-full inline-flex items-center justify-center gap-2 rounded-md border border-border-strong px-3 py-2 text-sm hover:bg-destructive/10 hover:border-destructive hover:text-destructive transition"
          >
            <LogOut className="h-4 w-4" /> Sign out
          </button>
        </div>
      </aside>

      {/* Main */}
      <div className="flex-1 min-w-0 flex flex-col">
        <header className="h-16 border-b border-border bg-surface/40 backdrop-blur-xl px-5 flex items-center gap-3 sticky top-0 z-30">
          <button
            onClick={() => setOpen((v) => !v)}
            className="lg:hidden h-9 w-9 grid place-items-center rounded-md border border-border"
          >
            <ChevronLeft className={`h-4 w-4 transition ${open ? "rotate-180" : ""}`} />
          </button>
          <h1 className="font-display text-lg font-bold">{title}</h1>
          <div className="ml-auto flex items-center gap-2">
            <Link to="/" className="text-xs text-muted-foreground hover:text-foreground">
              View site →
            </Link>
          </div>
        </header>
        <main className="flex-1 p-5 sm:p-8 overflow-x-hidden">{children}</main>
      </div>
    </div>
  );
}
