import { Link, useRouterState, useNavigate } from "@tanstack/react-router";
import { LayoutDashboard, BookOpen, User, LogOut, Shield, CreditCard, Menu, X } from "lucide-react";
import { useState, type ReactNode } from "react";
import { supabase } from "@/integrations/supabase/client";

interface Props { isAdmin: boolean; children: ReactNode }

export function DashboardLayout({ isAdmin, children }: Props) {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);

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

  const items = [
    { to: "/dashboard", icon: LayoutDashboard, label: "Dashboard" },
    { to: "/learn", icon: BookOpen, label: "My Course" },
    { to: "/my-payments", icon: CreditCard, label: "Payments" },
    { to: "/profile", icon: User, label: "Profile" },
  ];

  const NavLinks = () => (
    <>
      {items.map((it) => {
        const active = pathname === it.to || pathname.startsWith(it.to + "/");
        const Icon = it.icon;
        return (
          <Link key={it.to} to={it.to} onClick={() => setOpen(false)}
            className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition ${active ? "bg-primary/15 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"}`}>
            <Icon className="h-4 w-4" /> {it.label}
          </Link>
        );
      })}
      {isAdmin && (
        <Link to="/admin" onClick={() => setOpen(false)}
          className={`mt-2 flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-semibold transition ${pathname.startsWith("/admin") ? "bg-gold/15 text-gold" : "border border-dashed border-border text-foreground hover:bg-muted"}`}>
          <Shield className="h-4 w-4" /> Admin Panel
        </Link>
      )}
    </>
  );

  return (
    <div className="min-h-screen">
      {/* Mobile top bar */}
      <div className="sticky top-0 z-40 flex items-center justify-between border-b border-border bg-card/80 px-4 py-3 backdrop-blur md:hidden">
        <Link to="/" className="flex items-center gap-2">
          <div className="grid h-8 w-8 place-items-center rounded-md bg-gradient-primary"><span className="font-bold text-primary-foreground">B</span></div>
          <span className="font-display font-semibold">BO Mastery</span>
        </Link>
        <button onClick={() => setOpen((o) => !o)}>{open ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}</button>
      </div>

      <div className="mx-auto flex max-w-7xl">
        {/* Desktop sidebar */}
        <aside className="sticky top-0 hidden h-screen w-64 shrink-0 border-r border-border bg-sidebar p-4 md:block">
          <Link to="/" className="mb-8 flex items-center gap-2 px-2">
            <div className="grid h-9 w-9 place-items-center rounded-lg bg-gradient-primary shadow-glow"><span className="font-display font-bold text-primary-foreground">B</span></div>
            <div>
              <div className="font-display font-semibold">BO Mastery</div>
              <div className="text-[10px] uppercase tracking-wider text-muted-foreground">Student Portal</div>
            </div>
          </Link>
          <nav className="space-y-1"><NavLinks /></nav>
          <button onClick={signOut} className="absolute bottom-4 left-4 right-4 inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2.5 text-sm text-muted-foreground hover:bg-muted">
            <LogOut className="h-4 w-4" /> Sign out
          </button>
        </aside>

        {/* Mobile slide-over */}
        {open && (
          <div className="fixed inset-0 z-30 bg-background/95 backdrop-blur md:hidden">
            <nav className="space-y-1 p-4 pt-20"><NavLinks />
              <button onClick={signOut} className="mt-4 inline-flex w-full items-center gap-2 rounded-lg border border-border px-3 py-2.5 text-sm text-muted-foreground">
                <LogOut className="h-4 w-4" /> Sign out
              </button>
            </nav>
          </div>
        )}

        <main className="min-w-0 flex-1 p-4 md:p-8">{children}</main>
      </div>
    </div>
  );
}
