"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import {
  Settings,
  LogOut,
  ChevronsLeft,
  ChevronsRight,
  Command,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useUIStore } from "@/stores/ui-store";
import { createClient } from "@/lib/supabase/client";
import { WorkspaceSwitcher } from "@/components/layout/workspace-switcher";
import {
  orderSidebarItems,
  sidebarNavGroups,
  sidebarTopNav,
  type SidebarNavItem,
} from "@/lib/sidebar-navigation";

// ─── Section Label ─────────────────────────────────────────────────────────────

const SECTION_COLORS: Record<string, string> = {
  Produktivität: "text-sky-400/60",
  Wachstum:      "text-emerald-400/60",
  Finanzen:      "text-amber-400/60",
  Extras:        "text-white/20",
  System:        "text-violet-400/60",
};

function SectionLabel({ label, collapsed }: { label: string; collapsed: boolean }) {
  if (collapsed) return <div className="mx-3 my-3 h-px bg-white/[0.04]" />;
  const colorClass = SECTION_COLORS[label] ?? "text-white/20";
  return (
    <div className="flex items-center gap-2 px-3 pb-1 pt-5">
      <div className={cn("h-px flex-1 bg-current opacity-20", colorClass)} />
      <p className={cn("text-[9px] font-bold uppercase tracking-[0.18em]", colorClass)}>
        {label}
      </p>
      <div className={cn("h-px flex-1 bg-current opacity-20", colorClass)} />
    </div>
  );
}

// ─── Sidebar ───────────────────────────────────────────────────────────────────

export function Sidebar() {
  const pathname = usePathname();
  const router = useRouter();
  const {
    favoriteSidebarItemIds,
    hiddenSidebarItemIds,
    initSidebarPreferences,
    sidebarCustomOrderIds,
    sidebarCollapsed,
    setCommandPaletteOpen,
    toggleSidebarCollapsed,
  } = useUIStore();
  const isVisible = (item: SidebarNavItem) => !hiddenSidebarItemIds.includes(item.id);
  const isFavorite = (item: SidebarNavItem) => favoriteSidebarItemIds.includes(item.id);
  const visibleTopNav = orderSidebarItems(
    sidebarTopNav.filter((item) => item.id !== "ai" && isVisible(item) && !isFavorite(item)),
    sidebarCustomOrderIds
  );
  const visibleFeaturedAI = sidebarTopNav.find((item) => item.id === "ai" && isVisible(item) && !isFavorite(item));
  const favoriteItems = orderSidebarItems(
    [
      ...sidebarTopNav,
      ...sidebarNavGroups.flatMap((group) => group.items),
    ].filter((item) => isVisible(item) && isFavorite(item)),
    sidebarCustomOrderIds
  );
  const visibleGroups = sidebarNavGroups
    .map((group) => ({
      ...group,
      items: orderSidebarItems(
        group.items.filter((item) => isVisible(item) && !isFavorite(item)),
        sidebarCustomOrderIds
      ),
    }))
    .filter((group) => group.items.length > 0);

  useEffect(() => {
    initSidebarPreferences();
  }, [initSidebarPreferences]);

  async function handleSignOut() {
    const supabase = createClient();
    await supabase.auth.signOut();
    router.push("/login");
    router.refresh();
  }

  function NavItem({
    item,
    accent,
  }: {
    item: SidebarNavItem;
    accent?: string;
  }) {
    const isActive =
      item.href === "/"
        ? pathname === "/"
        : item.href === "/focus"
        ? pathname === "/focus" || (pathname.startsWith("/focus/") && !pathname.startsWith("/focus/rooms"))
        : pathname === item.href || pathname.startsWith(item.href + "/");

    return (
      <Link
        href={item.href}
        className={cn(
          "group flex items-center gap-3 rounded-lg px-3 py-[7px] text-[13px] font-medium transition-all duration-150",
          isActive
            ? "bg-white/[0.07] text-white shadow-[inset_0_0.5px_0_rgba(255,255,255,0.06)]"
            : "text-white/40 hover:bg-white/[0.04] hover:text-white/70"
        )}
        title={sidebarCollapsed ? item.name : undefined}
      >
        <item.icon
          className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            isActive
              ? (accent ?? "text-white/90")
              : "text-white/30 group-hover:text-white/50"
          )}
        />
        {!sidebarCollapsed && <span>{item.name}</span>}
      </Link>
    );
  }

  return (
    <aside
      className={cn(
        "hidden md:flex flex-col h-full transition-all duration-200 bg-sidebar border-r border-sidebar-border",
        sidebarCollapsed ? "w-[60px]" : "w-[220px]"
      )}
    >
      {/* Logo + Collapse */}
      <div className="flex h-16 items-center px-3 border-b border-sidebar-border">
        {!sidebarCollapsed && (
          <Link href="/" className="flex items-center gap-0">
            <Image
              src="/mindavio-logo.png"
              alt="Mindavio"
              width={104}
              height={104}
              className="rounded-lg"
              style={{ filter: "brightness(1.3) saturate(2.2) contrast(1.1)" }}
            />
            <span className="-ml-7 text-[12px] font-semibold tracking-wide text-gray-600 dark:text-white/75 dark:[text-shadow:0_0_12px_rgba(255,255,255,0.45)]">Mindavio</span>
          </Link>
        )}
        <button
          onClick={toggleSidebarCollapsed}
          className={cn(
            "rounded-md p-1.5 text-white/20 transition-colors hover:bg-white/[0.04] hover:text-white/40 cursor-pointer",
            sidebarCollapsed ? "mx-auto" : "ml-auto"
          )}
        >
          {sidebarCollapsed ? <ChevronsRight className="h-4 w-4" /> : <ChevronsLeft className="h-4 w-4" />}
        </button>
      </div>

      {/* ⌘K Trigger */}
      {!sidebarCollapsed && (
        <div className="px-3 pt-3">
          <button
            onClick={() => setCommandPaletteOpen(true)}
            className="flex w-full items-center gap-2.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-[12px] text-white/30 transition-all hover:border-white/[0.1] hover:bg-white/[0.04] hover:text-white/50 cursor-pointer"
          >
            <Command className="h-3.5 w-3.5" />
            <span>Command</span>
            <kbd className="ml-auto rounded bg-white/[0.06] px-1.5 py-0.5 font-mono text-[9px] text-white/25">⌘K</kbd>
          </button>
        </div>
      )}

      {/* Workspace */}
      <div className="px-3 pt-3">
        <WorkspaceSwitcher compact={sidebarCollapsed} />
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto overscroll-contain px-2 py-3 scrollbar-none">

        {/* AI — eigener Block, visuell abgesetzt */}
        {visibleFeaturedAI && (
        <div className="mb-3">
          <Link
            href={visibleFeaturedAI.href}
            className={cn(
              "flex items-center gap-3 rounded-xl border px-3 py-2.5 text-[13px] font-semibold transition-all duration-150",
              pathname === "/ai" || pathname.startsWith("/ai/")
                ? "border-indigo-500/30 bg-indigo-500/[0.12] text-indigo-300 shadow-sm shadow-indigo-500/10"
                : "border-white/[0.06] bg-white/[0.02] text-white/50 hover:border-indigo-500/20 hover:bg-indigo-500/[0.07] hover:text-indigo-300/80"
            )}
          >
            <visibleFeaturedAI.icon className={cn(
              "h-4 w-4 shrink-0 transition-colors",
              pathname === "/ai" || pathname.startsWith("/ai/")
                ? "text-indigo-400"
                : "text-white/30"
            )} />
            {!sidebarCollapsed && <span>{visibleFeaturedAI.name}</span>}
          </Link>
        </div>
        )}

        {/* Ganz oben — kein Label */}
        {favoriteItems.length > 0 && (
          <div className="mb-2">
            <SectionLabel label="Dock" collapsed={sidebarCollapsed} />
            <div className="space-y-0.5">
              {favoriteItems.map((item) => <NavItem key={item.id} item={item} accent="text-sky-300" />)}
            </div>
          </div>
        )}

        {visibleTopNav.length > 0 && (
          <div className="space-y-0.5">
            {visibleTopNav.map((item) => <NavItem key={item.id} item={item} />)}
          </div>
        )}

        {visibleGroups.map((group) => (
          <div key={group.id}>
            <SectionLabel label={group.label} collapsed={sidebarCollapsed} />
            <div className="space-y-0.5">
              {group.items.map((item) => <NavItem key={item.id} item={item} />)}
            </div>
          </div>
        ))}
      </nav>

      {/* Bottom */}
      <div className="space-y-0.5 border-t border-sidebar-border px-2 py-3">
        <Link
          href="/settings"
          className={cn(
            "flex items-center gap-3 rounded-lg px-3 py-[7px] text-[13px] font-medium transition-all duration-150",
            pathname.startsWith("/settings")
              ? "bg-white/[0.07] text-white"
              : "text-white/30 hover:bg-white/[0.04] hover:text-white/50"
          )}
          title={sidebarCollapsed ? "Settings" : undefined}
        >
          <Settings className="h-4 w-4 shrink-0" />
          {!sidebarCollapsed && <span>Settings</span>}
        </Link>
        <button
          onClick={handleSignOut}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-[7px] text-[13px] font-medium text-white/25 transition-all duration-150 hover:bg-white/[0.04] hover:text-white/40 cursor-pointer"
          title={sidebarCollapsed ? "Sign out" : undefined}
        >
          <LogOut className="h-4 w-4 shrink-0" />
          {!sidebarCollapsed && <span>Sign out</span>}
        </button>
      </div>
    </aside>
  );
}
