import { useEffect, useState } from "react";
import { Link } from "@tanstack/react-router";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import {
  ChevronsLeft,
  ChevronsRight,
  LayoutDashboard,
  FileText,
  ListChecks,
  Users,
  Settings,
  TrendingUp,
} from "lucide-react";

import { Brand } from "@/components/brand/Brand";
import { Gem } from "@/components/brand/Gem";
import { useAuth } from "@/lib/auth";
import { formatRubisToHours } from "@/lib/format";
import { cn } from "@/lib/utils";
import { NavLink } from "./NavLink";

const STORAGE_KEY = "rubis.sidebar.collapsed";

/**
 * Sidebar desktop — repliable.
 *
 *  - Déployée (240px)  : brand + nav avec labels + compteur rubis en bas
 *  - Repliée  (64px)   : juste les icônes (tooltip au hover) + gem du brand
 *
 * Le choix est persisté en localStorage (`rubis.sidebar.collapsed`) pour
 * survivre aux reloads. Toggle via un petit bouton chevron en bas.
 *
 * Le compteur rubis disparaît en mode replié (l'écran est trop étroit pour
 * en faire quelque chose de lisible) — on le retrouve en dépliant. La gem
 * en haut reste, donc l'identité de marque ne disparaît jamais.
 */
export function AppSidebar({ rubisThisMonth = 0 }: { rubisThisMonth?: number }) {
  const { user: _user } = useAuth();
  const [collapsed, setCollapsed] = useState(false);

  // Lecture localStorage à l'init (côté client uniquement).
  useEffect(() => {
    if (typeof window === "undefined") return;
    setCollapsed(window.localStorage.getItem(STORAGE_KEY) === "1");
  }, []);

  const toggle = () => {
    setCollapsed((prev) => {
      const next = !prev;
      if (typeof window !== "undefined") {
        window.localStorage.setItem(STORAGE_KEY, next ? "1" : "0");
      }
      return next;
    });
  };

  return (
    <aside
      className={cn(
        "hidden lg:flex h-screen sticky top-0 shrink-0 flex-col border-r border-line bg-cream-2/60 py-6",
        "transition-[width,padding] duration-200 ease-out",
        collapsed ? "w-[68px] px-2" : "w-[240px] px-4",
      )}
    >
      <Link
        to="/"
        className={cn(
          "mb-10 flex items-center justify-center",
          collapsed ? "px-0" : "px-2 justify-start",
        )}
        aria-label="Accueil Rubis"
      >
        {collapsed ? <Brand onlyImage gemSize={28} /> : <Brand />}
      </Link>

      <nav className="flex flex-col gap-1">
        <NavLink
          to="/"
          icon={<LayoutDashboard size={17} />}
          label="Dashboard"
          collapsed={collapsed}
        />
        <NavLink
          to="/factures"
          icon={<FileText size={17} />}
          label="Factures"
          collapsed={collapsed}
        />
        <NavLink
          to="/plans"
          icon={<ListChecks size={17} />}
          label="Plans de relance"
          collapsed={collapsed}
        />
        <NavLink
          to="/clients"
          icon={<Users size={17} />}
          label="Clients"
          collapsed={collapsed}
        />
        <NavLink
          to="/insights"
          icon={<TrendingUp size={17} />}
          label="Insights"
          collapsed={collapsed}
        />
        <NavLink
          to="/parametres"
          icon={<Settings size={17} />}
          label="Paramètres"
          collapsed={collapsed}
        />
      </nav>

      <div className="mt-auto flex flex-col gap-3">
        {collapsed ? (
          <RubisCounterCompact value={rubisThisMonth} />
        ) : (
          <div className="rounded-soft border border-line bg-white px-3.5 py-3">
            <p className="text-[10.5px] font-semibold uppercase tracking-[0.12em] text-ink-3">
              Rubis ce mois
            </p>
            <div className="mt-1.5 flex items-end gap-2">
              <Gem size={18} />
              <span className="font-display text-[22px] font-bold leading-none tabular-nums">
                {rubisThisMonth}
              </span>
            </div>
            <p className="mt-1 text-[11px] text-ink-3">
              ≈ {formatRubisToHours(rubisThisMonth)} libérées
            </p>
          </div>
        )}

        {/* Toggle replier / déplier */}
        <button
          type="button"
          onClick={toggle}
          aria-label={collapsed ? "Déplier la sidebar" : "Replier la sidebar"}
          title={collapsed ? "Déplier" : "Replier"}
          className={cn(
            "flex h-8 items-center justify-center rounded-default border border-line bg-white text-ink-3 cursor-pointer",
            "transition-colors hover:text-rubis hover:border-rubis",
            "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rubis-glow",
          )}
        >
          {collapsed ? (
            <ChevronsRight size={14} aria-hidden="true" />
          ) : (
            <ChevronsLeft size={14} aria-hidden="true" />
          )}
        </button>
      </div>
    </aside>
  );
}

/**
 * Compteur rubis ultra-compact pour le mode replié — gem + chiffre empilés
 * verticalement, tooltip au hover qui rappelle "Rubis ce mois · ≈ Xh libérées".
 */
function RubisCounterCompact({ value }: { value: number }) {
  return (
    <TooltipPrimitive.Provider delayDuration={200}>
      <TooltipPrimitive.Root>
        <TooltipPrimitive.Trigger asChild>
          <div
            className={cn(
              "flex flex-col items-center justify-center gap-0.5 rounded-soft border border-line bg-white py-2",
              "cursor-default",
            )}
            role="status"
            aria-label={`${value} rubis ce mois, soit ${formatRubisToHours(value)} libérées`}
          >
            <Gem size={16} />
            <span className="font-display text-[15px] font-bold leading-none tabular-nums text-ink">
              {value}
            </span>
          </div>
        </TooltipPrimitive.Trigger>
        <TooltipPrimitive.Portal>
          <TooltipPrimitive.Content
            side="right"
            sideOffset={8}
            className={cn(
              "z-50 rounded-default bg-ink px-2.5 py-1.5 text-[12px] font-medium text-white shadow-soft",
              "data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95",
            )}
          >
            <span className="font-semibold">Rubis ce mois</span>
            <span className="text-ink-3"> · ≈ {formatRubisToHours(value)} libérées</span>
            <TooltipPrimitive.Arrow className="fill-ink" width={8} height={4} />
          </TooltipPrimitive.Content>
        </TooltipPrimitive.Portal>
      </TooltipPrimitive.Root>
    </TooltipPrimitive.Provider>
  );
}
