"use client";

import { useAuth } from "@/lib/auth";
import { useRouter, usePathname } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import Navbar from "@/components/layout/Navbar";
import MobileNav from "@/components/layout/MobileNav";
import {
  LayoutDashboard, Receipt, ArrowLeftRight, Settings, LogOut,
  Loader2, ChevronLeft, ChevronRight, BarChart3, ShieldCheck
} from "lucide-react";

const sidebarItems = [
  { label: "Dashboard", href: "/dashboard", icon: LayoutDashboard },
  { label: "Transaksi", href: "/dashboard/transactions", icon: Receipt },
  { label: "Mutasi", href: "/dashboard/mutations", icon: ArrowLeftRight },
  { label: "Laporan", href: "/dashboard/reports", icon: BarChart3 },
  { label: "Pengaturan", href: "/dashboard/settings", icon: Settings },
];

export default function DashboardLayout({ children }: { children: ReactNode }) {
  const { user, loading, logout } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    if (!loading && !user) {
      router.replace("/login");
    }
  }, [loading, user, router]);

  if (loading || !user) {
    return (
      <>
        <Navbar />
        <main className="min-h-screen flex items-center justify-center pt-20">
          <div className="text-center">
            <Loader2 size={40} className="mx-auto text-primary animate-spin mb-4" />
            <p className="text-muted">Memuat dashboard...</p>
          </div>
        </main>
      </>
    );
  }

  const handleLogout = async () => {
    await logout();
    router.replace("/");
  };

  return (
    <>
      <Navbar />
      <div className="flex min-h-screen pt-[60px] bg-dark overflow-x-hidden">
        {/* ─── Sidebar (desktop) ─── */}
        <aside className={`hidden lg:flex flex-col sticky top-[60px] h-[calc(100vh-60px)] transition-all duration-300 border-r border-dark-border bg-dark-surface/30 ${collapsed ? "w-[72px]" : "w-[240px]"}`}>
          
          {/* Logo / Title Area in Sidebar (Optional, leaving empty space or padding) */}
          <div className="pt-8 px-4 pb-4">
             {/* Empty space to align with Bangjeff's clean look */}
          </div>

          {/* Nav items */}
          <nav className="flex-1 px-4 space-y-1">
            {sidebarItems.map((item) => {
              const Icon = item.icon;
              const isActive = pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-all group ${
                    isActive
                      ? "bg-gradient-to-r from-primary/20 to-transparent text-white border-l-2 border-primary"
                      : "text-muted hover:text-white hover:bg-white/5 border-l-2 border-transparent"
                  } ${collapsed ? "justify-center !px-2 border-l-0" : ""}`}
                  title={collapsed ? item.label : undefined}
                >
                  <Icon size={18} className={`${isActive ? "text-primary" : "text-muted group-hover:text-white"} transition-colors`} />
                  {!collapsed && <span>{item.label}</span>}
                </Link>
              );
            })}
            {/* Admin Panel link */}
            {user.role === "admin" && (
              <Link
                href="/admin"
                className={`flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-all group text-red-400 hover:bg-red-500/10 border-l-2 border-transparent ${collapsed ? "justify-center !px-2 border-l-0" : ""}`}
                title={collapsed ? "Admin Panel" : undefined}
              >
                <ShieldCheck size={18} className="text-red-400" />
                {!collapsed && <span>Admin Panel</span>}
              </Link>
            )}
          </nav>

          {/* Bottom actions */}
          <div className="p-4 space-y-1 mb-4">
            <button
              onClick={handleLogout}
              className={`flex items-center gap-3 w-full px-4 py-3 rounded-lg text-sm font-medium text-red-500 hover:bg-red-500/10 transition-all ${collapsed ? "justify-center !px-2" : "border-l-2 border-transparent"}`}
              title={collapsed ? "Keluar" : undefined}
            >
              <LogOut size={18} />
              {!collapsed && <span>Keluar</span>}
            </button>
            <button
              onClick={() => setCollapsed(!collapsed)}
              className={`flex items-center gap-3 w-full px-4 py-3 rounded-lg text-sm font-medium text-muted hover:text-white hover:bg-white/5 transition-all ${collapsed ? "justify-center !px-2" : "border-l-2 border-transparent"}`}
            >
              {collapsed ? <ChevronRight size={18} /> : <ChevronLeft size={18} />}
              {!collapsed && <span>Perkecil</span>}
            </button>
          </div>
        </aside>

        {/* ─── Main content ─── */}
        <main className="flex-1 pb-8 min-h-[calc(100vh-60px)] min-w-0 overflow-x-hidden">
          <div className="lg:hidden bg-dark-surface border-b border-dark-border overflow-x-auto scrollbar-none">
            <div className="flex items-center gap-2 px-4 py-3 min-w-max">
              {sidebarItems.map((item) => {
                const Icon = item.icon;
                const isActive = pathname === item.href;
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs font-bold whitespace-nowrap transition-all border ${
                      isActive
                        ? "bg-primary/10 text-primary border-primary/20"
                        : "bg-white/5 text-muted hover:text-white border-transparent"
                    }`}
                  >
                    <Icon size={14} />
                    {item.label}
                  </Link>
                );
              })}
            </div>
          </div>
          
          <div className="p-4 md:p-6 lg:p-8 max-w-7xl mx-auto">
            {children}
          </div>
        </main>
      </div>
      <MobileNav />
    </>
  );
}
