"use client";

import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import {
  Menu,
  X,
  LayoutDashboard,
  LogOut,
  MessageSquare,
  Briefcase,
  FileText,
  FolderGit2,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { ThemeToggle } from "@/components/ui/ThemeToggle";

const dashboardLinks = [
  { label: "Overview", href: "/dashboard", icon: LayoutDashboard },
  { label: "Messages", href: "/dashboard/messages", icon: MessageSquare },
  { label: "Experience", href: "/dashboard/experience", icon: Briefcase },
  { label: "Blog", href: "/dashboard/blog", icon: FileText },
  { label: "Projects", href: "/dashboard/projects", icon: FolderGit2 },
];

export function DashboardSidebar() {
  const pathname = usePathname();
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [mounted, setMounted] = useState(false);

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

  // Hide sidebar entirely if user is on login page
  if (pathname === "/dashboard/auth") return null;

  if (!mounted) return null; // Prevent hydration mismatch

  return (
    <>
      {/* Desktop Sidebar (Sticky) */}
      <motion.aside
        initial={false}
        animate={{ width: isCollapsed ? 80 : 256 }}
        transition={{ duration: 0.3, ease: "easeInOut" }}
        className="hidden md:flex flex-col sticky top-0 h-screen bg-background border-r border-border/50 shrink-0 z-40 group/sidebar"
      >
        <div className="flex items-center p-4 h-16 border-b border-border/50">
          <Link
            href="/dashboard"
            className={cn(
              "flex items-center gap-2 group w-full",
              isCollapsed && "justify-center",
            )}
          >
            <div className="w-8 h-8 shrink-0 rounded-md bg-primary/20 border border-primary/30 flex items-center justify-center group-hover:bg-primary/30 transition-colors">
              <LayoutDashboard size={16} className="text-primary" />
            </div>
            {!isCollapsed && (
              <span className="font-display font-semibold text-foreground text-sm tracking-wide whitespace-nowrap overflow-hidden">
                Admin<span className="text-primary">Panel</span>
              </span>
            )}
          </Link>
        </div>

        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className="absolute -right-3.5 top-20 bg-background border border-border rounded-full p-1.5 hover:bg-surface-elevated text-foreground-muted hover:text-foreground z-50 opacity-0 group-hover/sidebar:opacity-100 transition-opacity"
          aria-label="Toggle Sidebar"
        >
          {isCollapsed ? <ChevronRight size={14} /> : <ChevronLeft size={14} />}
        </button>

        <div className="flex-1 py-6 flex flex-col gap-2 px-3 overflow-y-auto overflow-x-hidden">
          {dashboardLinks.map((link) => {
            const Icon = link.icon;
            const isActive =
              link.href === "/dashboard"
                ? pathname === "/dashboard"
                : pathname.startsWith(link.href);

            return (
              <Link
                key={link.href}
                href={link.href}
                title={isCollapsed ? link.label : undefined}
                className={cn(
                  "flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors overflow-hidden group/link",
                  isActive
                    ? "bg-primary/10 text-primary font-medium"
                    : "text-foreground-muted hover:bg-surface-elevated hover:text-foreground",
                  isCollapsed && "justify-center px-0",
                )}
              >
                <Icon
                  size={18}
                  className={cn(
                    "shrink-0",
                    isActive
                      ? "text-primary"
                      : "text-foreground-muted group-hover/link:text-foreground",
                  )}
                />
                {!isCollapsed && (
                  <span className="whitespace-nowrap">{link.label}</span>
                )}
              </Link>
            );
          })}
        </div>

        <div className="p-4 border-t border-border/50 flex flex-col gap-2 relative">
          {!isCollapsed && (
            <div className="flex items-center justify-between px-3 py-2">
              <span className="text-sm text-foreground-muted font-medium">
                Theme
              </span>
              <ThemeToggle />
            </div>
          )}
          {isCollapsed && (
            <div className="flex justify-center py-2">
              <ThemeToggle />
            </div>
          )}
          <button
            className={cn(
              "flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors w-full text-destructive hover:bg-destructive/10 hover:text-destructive overflow-hidden group/logout",
              isCollapsed && "justify-center px-0",
            )}
            title={isCollapsed ? "Logout" : undefined}
          >
            <LogOut
              size={18}
              className="shrink-0 group-hover/logout:text-destructive text-destructive"
            />
            {!isCollapsed && (
              <span className="font-medium whitespace-nowrap">Logout</span>
            )}
          </button>
        </div>
      </motion.aside>

      {/* Mobile Header (Fixed) */}
      <div className="md:hidden fixed top-0 left-0 right-0 h-16 bg-background/90 backdrop-blur-xl border-b border-border/50 z-40 flex items-center justify-between px-4">
        <Link href="/dashboard" className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-md bg-primary/20 border border-primary/30 flex items-center justify-center">
            <LayoutDashboard size={14} className="text-primary" />
          </div>
          <span className="font-display font-semibold text-foreground text-sm tracking-wide">
            Admin<span className="text-primary">Panel</span>
          </span>
        </Link>
        <div className="flex items-center gap-2">
          <ThemeToggle />
          <button
            onClick={() => setMobileOpen(true)}
            className="p-2 -mr-2 rounded-lg hover:bg-surface-elevated transition-colors text-foreground"
            aria-label="Open menu"
          >
            <Menu size={20} />
          </button>
        </div>
      </div>

      {/* Mobile Sidebar Off-Canvas */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setMobileOpen(false)}
            className="md:hidden fixed inset-0 bg-background/80 backdrop-blur-sm z-50 cursor-pointer"
          />
        )}
      </AnimatePresence>

      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ x: "-100%" }}
            animate={{ x: 0 }}
            exit={{ x: "-100%" }}
            transition={{ type: "spring", bounce: 0, duration: 0.4 }}
            className="md:hidden fixed top-0 left-0 bottom-0 w-[280px] bg-background border-r border-border z-50 flex flex-col shadow-2xl"
          >
            <div className="flex items-center justify-between p-4 h-16 border-b border-border/50">
              <Link
                href="/dashboard"
                className="flex items-center gap-2"
                onClick={() => setMobileOpen(false)}
              >
                <div className="w-8 h-8 rounded-md bg-primary/20 border border-primary/30 flex items-center justify-center">
                  <LayoutDashboard size={16} className="text-primary" />
                </div>
                <span className="font-display font-semibold text-foreground text-sm tracking-wide">
                  Admin<span className="text-primary">Panel</span>
                </span>
              </Link>
              <button
                onClick={() => setMobileOpen(false)}
                className="p-2 rounded-lg hover:bg-surface-elevated transition-colors text-foreground-muted"
                aria-label="Close menu"
              >
                <X size={20} />
              </button>
            </div>

            <div className="flex-1 py-6 px-4 flex flex-col gap-2 overflow-y-auto">
              <span className="text-xs font-semibold text-foreground-muted mb-2 px-3 uppercase tracking-wider">
                Navigation
              </span>
              {dashboardLinks.map((link) => {
                const Icon = link.icon;
                const isActive =
                  link.href === "/dashboard"
                    ? pathname === "/dashboard"
                    : pathname.startsWith(link.href);

                return (
                  <Link
                    key={link.href}
                    href={link.href}
                    onClick={() => setMobileOpen(false)}
                    className={cn(
                      "flex items-center gap-3 px-3 py-3 rounded-lg transition-colors",
                      isActive
                        ? "bg-primary/10 text-primary font-medium"
                        : "text-foreground-muted hover:bg-surface-elevated hover:text-foreground",
                    )}
                  >
                    <Icon
                      size={18}
                      className={cn(
                        isActive ? "text-primary" : "text-foreground-muted",
                      )}
                    />
                    <span>{link.label}</span>
                  </Link>
                );
              })}
            </div>

            <div className="p-4 border-t border-border/50 flex flex-col gap-2">
              <button
                className="flex items-center gap-3 px-3 py-3 rounded-lg transition-colors w-full text-destructive hover:bg-destructive/10"
                onClick={() => setMobileOpen(false)}
              >
                <LogOut size={18} />
                <span className="font-medium">Logout</span>
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
