import { useState } from "react";
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import {
  LayoutDashboard,
  ArrowLeftRight,
  Tag,
  Wallet,
  History,
  Menu,
  X,
  LogOut,
  ChevronRight,
} from "lucide-react";
import { useAuthStore } from "../stores/auth";
import { logoutUser } from "../api/client";
import { useToast } from "../context/ToastContext";

const NAV_ITEMS = [
  { to: "/", icon: LayoutDashboard, label: "Dashboard", end: true },
  { to: "/transactions", icon: ArrowLeftRight, label: "Transactions", end: false },
  { to: "/categories", icon: Tag, label: "Catégories", end: false },
  { to: "/budgets", icon: Wallet, label: "Budgets", end: false },
  { to: "/history", icon: History, label: "Historique", end: false },
];

export default function Layout() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const { user, refreshToken, logout } = useAuthStore();
  const navigate = useNavigate();
  const { addToast } = useToast();

  const handleLogout = async () => {
    try {
      if (refreshToken) await logoutUser(refreshToken);
    } catch {
      // best-effort logout
    } finally {
      logout();
      navigate("/login");
      addToast({ type: "info", message: "Déconnecté avec succès" });
    }
  };

  const navLinkClass = ({ isActive }: { isActive: boolean }) =>
    `flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
      isActive
        ? "bg-primary text-white"
        : "text-slate-300 hover:bg-slate-700 hover:text-white"
    }`;

  const SidebarContent = () => (
    <div className="flex h-full flex-col">
      {/* Logo */}
      <div className="flex h-16 items-center border-b border-slate-700 px-4">
        <span className="text-lg font-bold text-white">Budget Tracker</span>
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto px-3 py-4">
        <ul className="space-y-1">
          {NAV_ITEMS.map(({ to, icon: Icon, label, end }) => (
            <li key={to}>
              <NavLink
                to={to}
                end={end}
                className={navLinkClass}
                onClick={() => setSidebarOpen(false)}
              >
                <Icon size={18} />
                {label}
                <ChevronRight size={14} className="ml-auto opacity-40" />
              </NavLink>
            </li>
          ))}
        </ul>
      </nav>

      {/* User / Logout */}
      <div className="border-t border-slate-700 p-4">
        <div className="mb-2 truncate text-xs text-slate-400">
          {user?.full_name ?? user?.email ?? "—"}
        </div>
        <button
          onClick={handleLogout}
          className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm text-slate-300 transition-colors hover:bg-slate-700 hover:text-white"
        >
          <LogOut size={16} />
          Déconnexion
        </button>
      </div>
    </div>
  );

  return (
    <div className="flex h-screen overflow-hidden">
      {/* Desktop sidebar */}
      <aside className="hidden w-60 shrink-0 bg-slate-800 lg:flex lg:flex-col">
        <SidebarContent />
      </aside>

      {/* Mobile overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/50 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Mobile sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 w-60 transform bg-slate-800 transition-transform duration-200 lg:hidden ${
          sidebarOpen ? "translate-x-0" : "-translate-x-full"
        }`}
      >
        <button
          onClick={() => setSidebarOpen(false)}
          className="absolute right-3 top-4 text-slate-400 hover:text-white"
          aria-label="Fermer le menu"
        >
          <X size={20} />
        </button>
        <SidebarContent />
      </aside>

      {/* Main content */}
      <div className="flex flex-1 flex-col overflow-hidden">
        {/* Mobile header */}
        <header className="flex h-14 items-center border-b bg-white px-4 lg:hidden">
          <button
            onClick={() => setSidebarOpen(true)}
            className="text-slate-600 hover:text-slate-900"
            aria-label="Ouvrir le menu"
          >
            <Menu size={22} />
          </button>
          <span className="ml-3 font-semibold text-slate-800">
            Budget Tracker
          </span>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-y-auto bg-gray-50 p-4 lg:p-6">
          <Outlet />
        </main>
      </div>
    </div>
  );
}
