"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMemo, useState, useCallback, useEffect } from "react";
import { useTheme } from "next-themes";
import * as Icons from "lucide-react";
import { PanelLeftClose, PanelLeftOpen } from "lucide-react";
import { buildNavigation } from "@/config/navigation";
import { COMPANIES } from "@/config/companies";
import { useFeatureFlag } from "@/core/feature-flags";
import { useAuth } from "@/core/auth/auth-provider";
import { cn } from "@/shared/lib/utils";
import { ScrollArea } from "@/shared/components/ui/scroll-area";
import { Separator } from "@/shared/components/ui/separator";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/components/ui/tooltip";

const SIDEBAR_COLLAPSED_KEY = "sidebar:collapsed";

function DynamicIcon({
  name,
  className,
}: {
  name: string;
  className?: string;
}) {
  const pascalName = name.replace(/(^|-)([a-z])/g, (_, _p, c: string) =>
    c.toUpperCase(),
  );
  const IconComponent = (
    Icons as unknown as Record<
      string,
      React.ComponentType<{ className?: string }>
    >
  )[pascalName];
  if (!IconComponent) return <Icons.Circle className={className} />;
  return <IconComponent className={className} />;
}

function NavItem({
  item,
  isActive,
  collapsed,
}: {
  item: {
    id: string;
    label: string;
    icon: string;
    href: string;
    featureFlag: string;
  };
  isActive: boolean;
  collapsed: boolean;
}) {
  const enabled = useFeatureFlag(item.featureFlag);
  if (!enabled) return null;

  const linkClass = cn(
    "flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
    collapsed && "justify-center px-2",
    isActive
      ? "bg-accent text-accent-foreground font-medium"
      : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground",
  );

  if (collapsed) {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Link href={item.href} className={linkClass}>
            <DynamicIcon name={item.icon} className="h-4 w-4 shrink-0" />
          </Link>
        </TooltipTrigger>
        <TooltipContent side="right">
          <p>{item.label}</p>
        </TooltipContent>
      </Tooltip>
    );
  }

  return (
    <Link href={item.href} className={linkClass}>
      <DynamicIcon name={item.icon} className="h-4 w-4 shrink-0" />
      <span className="truncate">{item.label}</span>
    </Link>
  );
}

const LOGO_COMPANIES = ["beletage", "urban-switch", "studii-de-teren"] as const;

const ANIMATIONS = [
  "animate-[spin_0.5s_ease-in-out]",
  "animate-[bounce_0.5s_ease-in-out]",
  "animate-[ping_0.4s_ease-in-out]",
] as const;

const COMPANY_GLOW: Record<string, string> = {
  beletage: "hover:drop-shadow-[0_0_6px_#22B5AB]",
  "urban-switch": "hover:drop-shadow-[0_0_6px_#6366f1]",
  "studii-de-teren": "hover:drop-shadow-[0_0_6px_#f59e0b]",
};

const SECRET_COMBO = ["beletage", "urban-switch", "studii-de-teren"];

function SidebarLogos() {
  const [animatingId, setAnimatingId] = useState<string | null>(null);
  const [comboProgress, setComboProgress] = useState(0);
  const [showConfetti, setShowConfetti] = useState(false);
  const [mounted, setMounted] = useState(false);
  const { resolvedTheme } = useTheme();

  useEffect(() => setMounted(true), []);

  const isDark = mounted ? resolvedTheme === "dark" : false;

  useEffect(() => {
    if (comboProgress === 0) return;
    const timer = setTimeout(() => setComboProgress(0), 3000);
    return () => clearTimeout(timer);
  }, [comboProgress]);

  useEffect(() => {
    if (!showConfetti) return;
    const timer = setTimeout(() => setShowConfetti(false), 2000);
    return () => clearTimeout(timer);
  }, [showConfetti]);

  const handleLogoClick = useCallback(
    (companyId: string, e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      setAnimatingId(companyId);
      setTimeout(() => setAnimatingId(null), 500);

      if (SECRET_COMBO[comboProgress] === companyId) {
        const next = comboProgress + 1;
        if (next >= SECRET_COMBO.length) {
          setShowConfetti(true);
          setComboProgress(0);
        } else {
          setComboProgress(next);
        }
      } else if (SECRET_COMBO[0] === companyId) {
        setComboProgress(1);
      } else {
        setComboProgress(0);
      }
    },
    [comboProgress],
  );

  return (
    <div className="relative flex w-full items-center justify-center gap-3 overflow-hidden">
      {LOGO_COMPANIES.map((companyId, index) => {
        const company = COMPANIES[companyId];
        const lightSrc = company?.logo?.light;
        const darkSrc = company?.logo?.dark ?? company?.logo?.light;
        if (!lightSrc) return null;
        const isAnimating = animatingId === companyId;
        const animation = isAnimating
          ? ANIMATIONS[index % ANIMATIONS.length]
          : "";
        const glow = COMPANY_GLOW[companyId] ?? "";

        return (
          <button
            key={companyId}
            type="button"
            onClick={(e) => handleLogoClick(companyId, e)}
            className={cn(
              "relative min-w-0 flex-1 rounded-md p-0.5 transition-all duration-200 hover:scale-110 focus:outline-none",
              glow,
              isAnimating && animation,
            )}
            title={company.shortName}
          >
            <Image
              src={lightSrc}
              alt={company.shortName}
              width={200}
              height={40}
              className={cn(
                "h-7 w-full object-contain transition-opacity duration-300",
                isDark ? "hidden" : "block",
              )}
              suppressHydrationWarning
            />
            <Image
              src={darkSrc ?? lightSrc}
              alt={company.shortName}
              width={200}
              height={40}
              className={cn(
                "h-7 w-full object-contain transition-opacity duration-300",
                isDark ? "block" : "hidden",
              )}
              suppressHydrationWarning
            />
          </button>
        );
      })}

      {showConfetti && (
        <div className="pointer-events-none absolute -bottom-6 left-1/2 -translate-x-1/2 z-50">
          <div className="flex gap-0.5 animate-[fadeIn_0.2s_ease-in]">
            {["🎉", "✨", "🏗️", "✨", "🎉"].map((emoji, i) => (
              <span
                key={i}
                className="text-sm animate-[bounce_0.6s_ease-in-out]"
                style={{ animationDelay: `${i * 80}ms` }}
              >
                {emoji}
              </span>
            ))}
          </div>
          <p className="mt-0.5 whitespace-nowrap text-center text-[9px] font-bold text-primary animate-[pulse_0.5s_ease-in-out_infinite]">
            Echipa completă!
          </p>
        </div>
      )}
    </div>
  );
}

interface SidebarProps {
  collapsed: boolean;
  onToggle: () => void;
}

export function Sidebar({ collapsed, onToggle }: SidebarProps) {
  const pathname = usePathname();
  const navGroups = useMemo(() => buildNavigation(), []);
  const { user } = useAuth();

  const brandingLabel = useMemo(() => {
    if (!user?.name) return "ArchiTools";
    const firstName = user.name.split(" ")[0];
    if (!firstName) return "ArchiTools";
    return `${firstName}'s Tools`;
  }, [user?.name]);

  return (
    <TooltipProvider delayDuration={200}>
      <aside
        className={cn(
          "flex h-full shrink-0 flex-col border-r bg-card transition-[width] duration-200",
          collapsed ? "w-14" : "w-64",
        )}
      >
        {/* Header */}
        <div className={cn("border-b px-4 py-3", collapsed && "px-2")}>
          {collapsed ? (
            <div className="flex flex-col items-center gap-2">
              <Tooltip>
                <TooltipTrigger asChild>
                  <Link
                    href="/"
                    className="flex items-center justify-center rounded-md p-1 hover:bg-accent"
                  >
                    <Icons.Home className="h-5 w-5 text-primary" />
                  </Link>
                </TooltipTrigger>
                <TooltipContent side="right">ArchiTools</TooltipContent>
              </Tooltip>
            </div>
          ) : (
            <>
              <Link
                href="/"
                className="mb-2 flex w-full items-center justify-center"
                title="Panou principal"
              >
                <SidebarLogos />
              </Link>
              <Link
                href="/"
                className="block text-center text-base font-semibold tracking-wide transition-colors hover:text-primary"
                title="Panou principal"
              >
                {brandingLabel}
              </Link>
            </>
          )}
        </div>

        {/* Nav */}
        <ScrollArea className={cn("flex-1 py-3", collapsed ? "px-1" : "px-3")}>
          {/* Home link */}
          {collapsed ? (
            <Tooltip>
              <TooltipTrigger asChild>
                <Link
                  href="/"
                  className={cn(
                    "mb-1 flex items-center justify-center rounded-md px-2 py-2 text-sm transition-colors",
                    pathname === "/"
                      ? "bg-accent text-accent-foreground font-medium"
                      : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground",
                  )}
                >
                  <Icons.LayoutDashboard className="h-4 w-4" />
                </Link>
              </TooltipTrigger>
              <TooltipContent side="right">Panou principal</TooltipContent>
            </Tooltip>
          ) : (
            <Link
              href="/"
              className={cn(
                "mb-1 flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
                pathname === "/"
                  ? "bg-accent text-accent-foreground font-medium"
                  : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground",
              )}
            >
              <Icons.LayoutDashboard className="h-4 w-4" />
              <span>Panou principal</span>
            </Link>
          )}

          <Separator className="my-2" />

          {navGroups.map((group) => (
            <div key={group.category} className="mb-3">
              {!collapsed && (
                <p className="mb-1 px-3 text-xs font-medium uppercase tracking-wider text-muted-foreground/60">
                  {group.label}
                </p>
              )}
              {collapsed && <Separator className="my-1 opacity-30" />}
              {group.items.map((item) => (
                <NavItem
                  key={item.id}
                  item={item}
                  isActive={pathname.startsWith(item.href)}
                  collapsed={collapsed}
                />
              ))}
            </div>
          ))}
        </ScrollArea>

        {/* Collapse toggle button */}
        <div className={cn("border-t p-2", collapsed && "flex justify-center")}>
          <button
            onClick={onToggle}
            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-accent-foreground"
            title={collapsed ? "Extinde sidebar" : "Restrânge sidebar"}
          >
            {collapsed ? (
              <PanelLeftOpen className="h-4 w-4 shrink-0" />
            ) : (
              <>
                <PanelLeftClose className="h-4 w-4 shrink-0" />
                <span>Restrânge</span>
              </>
            )}
          </button>
        </div>
      </aside>
    </TooltipProvider>
  );
}
