"use client";

import { useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import {
  LayoutDashboard, FileText, Briefcase, ShoppingBag,
  Clock, Wrench, Settings, Mail, LogOut, Menu, X, ChevronRight,
} from "lucide-react";
import { cn } from "@/lib/utils";

const navItems = [
  { href: "/admin", label: "داشبورد", icon: LayoutDashboard, exact: true },
  { href: "/admin/posts", label: "نوشته‌ها", icon: FileText },
  { href: "/admin/projects", label: "پروژه‌ها", icon: Briefcase },
  { href: "/admin/products", label: "محصولات", icon: ShoppingBag },
  { href: "/admin/timeline", label: "تایم‌لاین", icon: Clock },
  { href: "/admin/uses", label: "ابزارها", icon: Wrench },
  { href: "/admin/messages", label: "پیام‌ها", icon: Mail },
  { href: "/admin/settings", label: "تنظیمات", icon: Settings },
];

interface Props {
  username?: string;
  unreadCount?: number;
}

export function AdminSidebar({ username, unreadCount = 0 }: Props) {
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);

  async function handleLogout() {
    await fetch("/api/admin/auth", { method: "DELETE" });
    router.push("/admin/login");
  }

  function isActive(href: string, exact?: boolean) {
    if (exact) return pathname === href;
    return pathname.startsWith(href);
  }

  const SidebarContent = () => (
    <div className="flex h-full flex-col">
      {/* Logo */}
      <div className="border-b border-white/10 p-6">
        <div className="font-mono text-xs text-accent mb-1">// admin panel</div>
        <div className="font-bold text-text-primary">biztaghavi.com</div>
        {username && (
          <div className="mt-1 text-xs text-text-secondary">خوش آمدی، {username}</div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 space-y-1 overflow-y-auto p-4">
        {navItems.map((item) => {
          const active = isActive(item.href, item.exact);
          return (
            <a
              key={item.href}
              href={item.href}
              onClick={() => setOpen(false)}
              className={cn(
                "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-all",
                active
                  ? "bg-accent/10 text-accent border border-accent/20"
                  : "text-text-secondary hover:bg-surface-hover hover:text-text-primary"
              )}
            >
              <item.icon size={16} className="shrink-0" />
              <span>{item.label}</span>
              {item.href === "/admin/messages" && unreadCount > 0 && (
                <span className="ms-auto flex h-5 min-w-5 items-center justify-center rounded-full bg-accent px-1 font-mono text-xs text-background">
                  {unreadCount}
                </span>
              )}
              {active && <ChevronRight size={12} className="ms-auto text-accent" />}
            </a>
          );
        })}
      </nav>

      {/* Footer */}
      <div className="border-t border-white/10 p-4 space-y-2">
        <a
          href="/"
          target="_blank"
          className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-text-secondary hover:text-text-primary hover:bg-surface-hover transition-all"
        >
          <ChevronRight size={14} className="rotate-180" />
          مشاهده سایت
        </a>
        <button
          onClick={handleLogout}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-danger/80 hover:text-danger hover:bg-danger/10 transition-all"
        >
          <LogOut size={16} />
          خروج
        </button>
      </div>
    </div>
  );

  return (
    <>
      {/* Mobile toggle */}
      <button
        className="fixed top-4 right-4 z-50 flex h-10 w-10 items-center justify-center rounded-lg border border-border bg-surface text-text-secondary lg:hidden"
        onClick={() => setOpen(!open)}
      >
        {open ? <X size={18} /> : <Menu size={18} />}
      </button>

      {/* Mobile overlay */}
      {open && (
        <div
          className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"
          onClick={() => setOpen(false)}
        />
      )}

      {/* Mobile sidebar */}
      <aside
        className={cn(
          "fixed inset-y-0 right-0 z-40 w-72 transform bg-surface border-l border-border transition-transform duration-300 lg:hidden",
          open ? "translate-x-0" : "translate-x-full"
        )}
      >
        <SidebarContent />
      </aside>

      {/* Desktop sidebar */}
      <aside className="hidden lg:flex lg:w-64 lg:flex-col lg:fixed lg:inset-y-0 lg:right-0 border-l border-border bg-surface">
        <SidebarContent />
      </aside>
    </>
  );
}
