"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  LayoutDashboard,
  Folder,
  Search,
  KeyRound,
  TrendingUp,
  Link as LinkIcon,
  FileText,
  Globe,
  ChevronRight,
  ChevronLeft,
  LogOut,
  Settings,
  ChevronDown,
} from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/Context/AuthProvider";
import axios from "axios";

const menu = [
  { label: "Dashboard", href: "/user/dashboard", icon: LayoutDashboard },
  { label: "Projects", href: "/user/dashboard/projects", icon: Folder },
  { label: "SEO Audit", href: "/user/dashboard/seo-audit", icon: Search },
  { label: "Keywords", href: "/user/dashboard/keywords", icon: KeyRound },
  {
    label: "Rank Tracking",
    href: "/user/dashboard/rank-tracking",
    icon: TrendingUp,
  },
  { label: "Backlinks", href: "/user/dashboard/backlinks", icon: LinkIcon },
  { label: "Reports", href: "/user/dashboard/reports", icon: FileText },
];

export default function Sidebar({ isOpen, onClose }) {
  const router = useRouter();
  const pathname = usePathname();
  const { authUser, logout } = useAuth();
  const [collapsed, setCollapsed] = useState(false);

  const isSettingsActive = pathname.startsWith("/user/dashboard/settings");

  const handleLogout = async () => {
    try {
      await axios.post(
        `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/user/logout`,
        {},
        { withCredentials: true },
      );

      toast.success("Logged out successfully");
    } catch (err) {
      toast.error("Logout failed. Please try again");
    } finally {
      logout();
      router.replace("/");
    }
  };

  return (
    <>
      {isOpen && (
        <div
          onClick={onClose}
          className="fixed inset-0 bg-black/40 z-40 md:hidden"
        />
      )}

      <aside
        className={`
    fixed md:static z-50 inset-y-0 left-0
    ${collapsed ? "w-20" : "w-65"}
    bg-[#1E293B]
    border-r border-white/10
    transition-all duration-300
    ${isOpen ? "translate-x-0" : "-translate-x-full"}
    md:translate-x-0
    flex flex-col h-screen
  `}
      >
        <div className="px-5 py-3 border-b border-[#FFFFFF1A]">
          <div
            className="flex items-center gap-1 cursor-pointer"
            onClick={() => router.push("/")}
          >
            <img src="/logo.png" alt="logo" className="w-8" />
            {!collapsed && (
              <span className="text-xl font-semibold text-white tracking-wide">
                AURRGANIC
              </span>
            )}
          </div>
        </div>

        {!collapsed && (
          <div className="px-5 py-4 border-b border-[#FFFFFF1A]">
            <p className="text-xs text-gray-400 tracking-wide mb-3">
              ACTIVE PROJECT
            </p>

            <div className="flex items-center justify-between bg-[#FFFFFF1A] border border-white/10 px-3 py-2.5 rounded-xl">
              <div className="flex items-center gap-2 text-gray-200 text-sm">
                <Globe size={16} className="text-[#794AFF]" />
                <span>acme-corp.com</span>
              </div>
              <ChevronDown size={16} className="text-gray-400" />
            </div>
          </div>
        )}

        <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-1 custom-scrollbar">
          {menu.map((item) => {
            const Icon = item.icon;

            const isActive =
              item.href === "/user/dashboard"
                ? pathname === "/user/dashboard"
                : pathname.startsWith(item.href);

            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={onClose}
                className={`
                  group flex items-center gap-3 px-3 py-2 rounded-xl
                  text-sm font-medium transition-all
                  ${
                    isActive
                      ? "bg-[#794AFF] text-white shadow-md"
                      : "text-[#99A1AF] hover:bg-white/5 hover:text-white"
                  }
                `}
              >
                <div className="w-8 h-8 flex items-center justify-center rounded-lg">
                  <Icon size={18} />
                </div>

                {!collapsed && <span>{item.label}</span>}
              </Link>
            );
          })}
        </nav>

        <div className="px-3 py-1 space-y-1 border-t border-[#FFFFFF1A]">
          <Link
            href="/user/dashboard/settings"
            className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm rounded-xl transition
    ${
      isSettingsActive
        ? "bg-[#794AFF] text-white shadow-md"
        : "text-[#99A1AF] hover:bg-white/5 hover:text-white"
    }
  `}
          >
            <div className="w-8 h-8 flex items-center justify-center rounded-lg">
              <Settings size={18} />
            </div>

            {!collapsed && "Settings"}
          </Link>

          <button
            onClick={handleLogout}
            className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-gray-400 hover:bg-white/5 hover:text-white rounded-xl transition"
          >
            <div className="w-8 h-8 flex items-center justify-center rounded-lg">
              <LogOut size={18} />
            </div>

            {!collapsed && "Sign Out"}
          </button>
        </div>

        <div className="hidden md:block relative">
          <button
            onClick={() => setCollapsed(!collapsed)}
            className="absolute -right-3 bottom-6 w-8 h-8 rounded-full bg-white text-black shadow flex items-center justify-center"
          >
            {collapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
          </button>
        </div>
      </aside>
    </>
  );
}
