"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { MessageSquare, Server, Settings, BookOpen, FileCode2, FolderOpen, ArrowUpCircle } from "lucide-react";
import { cn } from "@/lib/utils";
import { loadProfile, loadProfileFromServer, type UserProfile } from "@/lib/stores/profile";
import { fetchVersion, type VersionInfo } from "@/lib/api/settings";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";

const menuItems = [
  { name: "Nexus Chat", icon: MessageSquare, href: "/" },
  { name: "MCP Servers", icon: Server, href: "/tools" },
  { name: "Agent Skills", icon: BookOpen, href: "/skills" },
  { name: "Pages", icon: FileCode2, href: "/pages" },
  { name: "Workspace", icon: FolderOpen, href: "/workspace" },
  { name: "Settings", icon: Settings, href: "/settings" },
];

const PROFILE_DEFAULTS: UserProfile = {
  name: "", avatar: "",
  platformName: "Track Platform", platformSubtitle: "Nexus System",
  botName: "Nexus Platform Core", botAvatar: "",
};

export function Sidebar() {
  const pathname = usePathname();
  const [profile, setProfile] = useState<UserProfile>(PROFILE_DEFAULTS);
  const [version, setVersion] = useState<VersionInfo | null>(null);

  useEffect(() => {
    setProfile(loadProfile());
    loadProfileFromServer().then(setProfile).catch(() => {});
    fetchVersion().then(setVersion).catch(() => {});
    const handler = () => setProfile(loadProfile());
    window.addEventListener("profile-change", handler);
    return () => window.removeEventListener("profile-change", handler);
  }, []);

  return (
    <aside className="w-20 lg:w-64 border-r border-foreground/10 bg-foreground/[0.02] backdrop-blur-3xl h-screen flex flex-col transition-all duration-500 z-50 relative overflow-hidden shadow-[20px_0_80px_rgba(0,0,0,0.3)]">
      {/* Sidebar background decoration */}
      <div className="absolute inset-0 opacity-[0.03] pointer-events-none">
          <img src="/rubber-track.png" alt="" className="w-full h-full object-cover scale-150 rotate-12 grayscale" />
      </div>
      
      {/* Top Gloss Effect */}
      <div className="absolute top-0 left-0 right-0 h-[1px] bg-gradient-to-r from-transparent via-foreground/20 to-transparent" />

      <div className="p-8 flex items-center gap-4 border-b border-foreground/5 relative z-10">
        <div className="relative group">
            <div className="absolute inset-0 bg-primary/40 blur-2xl rounded-full opacity-30 group-hover:opacity-100 transition-opacity duration-700" />
            <div className="relative w-14 h-14 overflow-hidden bg-foreground/5 rounded-2xl border border-foreground/10 shadow-2xl flex items-center justify-center transition-all duration-500 group-hover:scale-105 group-hover:border-primary/50 group-hover:bg-foreground/10">
                <img src="/drb.png" alt={profile.platformName} className="w-10 h-10 object-contain drop-shadow-[0_0_12px_rgba(245,158,11,0.5)]" />
            </div>
        </div>
        <div className="flex flex-col hidden lg:flex">
            <span className="text-sm font-black tracking-widest text-foreground uppercase leading-tight drop-shadow-sm">{profile.platformName}</span>
            <span className="text-[10px] font-bold tracking-[0.3em] text-primary uppercase animate-pulse">{profile.platformSubtitle}</span>
        </div>
      </div>
      
      <nav className="flex-1 p-4 space-y-3 py-10 relative z-10">
        {menuItems.map((item) => {
          const isActive = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "group relative flex items-center gap-4 px-4 py-4 rounded-2xl transition-all duration-500",
                isActive 
                  ? "bg-foreground/[0.05] text-primary shadow-[0_8px_32px_rgba(0,0,0,0.3)] border border-foreground/10 backdrop-blur-md" 
                  : "text-muted-foreground/60 hover:text-foreground hover:bg-foreground/5"
              )}
            >
              <item.icon className={cn(
                "w-5 h-5 transition-all duration-500",
                isActive ? "text-primary scale-110 drop-shadow-[0_0_8px_var(--primary)]" : "opacity-40 group-hover:opacity-100"
              )} />
              <span className="text-[10px] font-black tracking-[0.2em] uppercase hidden lg:block">{item.name}</span>
              
              {isActive && (
                <div className="absolute right-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-primary rounded-l-full shadow-[0_0_20px_var(--primary)]" />
              )}
            </Link>
          );
        })}
      </nav>

      <div className="mt-auto p-8 space-y-6 relative z-10">
          <div className="hidden lg:block space-y-4">
              <div className="flex items-center justify-between text-[9px] uppercase font-black tracking-[0.2em] text-muted-foreground/40">
                  <span>Logic Core Engine</span>
                  <span className="text-primary/70 animate-pulse">Active</span>
              </div>
              <div className="h-0.5 w-full bg-foreground/5 rounded-full overflow-hidden">
                  <div className="h-full w-[94%] bg-gradient-to-r from-primary/40 via-primary to-orange-500 shadow-[0_0_15px_var(--primary)]" />
              </div>
          </div>
          
          <div className="flex items-center justify-center lg:justify-start gap-4 p-4 bg-foreground/5 rounded-2xl border border-foreground/5 backdrop-blur-md group hover:bg-foreground/10 transition-all duration-300">
              <div className="relative">
                  <div className="absolute inset-0 bg-primary/40 blur-md rounded-full animate-ping" />
                  <div className="w-2 h-2 rounded-full bg-primary shadow-[0_0_12px_var(--primary)]" />
              </div>
              <span className="text-[9px] font-black font-mono text-muted-foreground/80 uppercase tracking-widest hidden lg:block">System-Secure-Auth</span>
          </div>

          {version && (
            <HoverCard openDelay={200} closeDelay={100}>
              <HoverCardTrigger asChild>
                <div className={cn(
                  "flex items-center justify-center lg:justify-start gap-2 cursor-default select-none",
                  version.update_available ? "text-emerald-400" : "text-muted-foreground/40"
                )}>
                  {version.update_available && <ArrowUpCircle className="w-3 h-3 hidden lg:block" />}
                  <span className="text-[9px] font-black tracking-widest uppercase">
                    v{version.current}
                    {version.update_available && version.latest && (
                      <span> → v{version.latest}</span>
                    )}
                  </span>
                </div>
              </HoverCardTrigger>
              <HoverCardContent side="top" align="start" className="w-72 p-4 space-y-3 bg-background/95 backdrop-blur-xl border border-foreground/10">
                {version.update_available ? (
                  <>
                    <p className="text-xs font-bold text-emerald-400">Update available</p>
                    <div className="space-y-1.5">
                      <code className="block text-[10px] bg-foreground/5 px-2 py-1.5 rounded-md font-mono text-foreground/80">pipx upgrade nexus-agent-platform</code>
                      <code className="block text-[10px] bg-foreground/5 px-2 py-1.5 rounded-md font-mono text-foreground/80">uv tool upgrade nexus-agent-platform</code>
                    </div>
                  </>
                ) : (
                  <p className="text-xs text-muted-foreground">You&apos;re on the latest version.</p>
                )}
              </HoverCardContent>
            </HoverCard>
          )}
      </div>
    </aside>
  );
}
