"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, type ReactNode } from "react";
import logoImg from '../../../public/assets/logo/logo2.png'
import { LogOut, SquareUser } from "lucide-react";
import { Button } from "../ui/button";
import { logoutUser } from "@/lib/api/auth";
import type { IconName, NavigationItem } from "@/config/dashboard-navigation";
import { getVisibleNavigation } from "@/lib/dashboard-permissions";
import { useDashboardAccess } from "@/hooks/use-dashboard-access";

function Icon({ name, className = "size-5" }: { name: IconName; className?: string }) {
  const paths: Record<IconName, ReactNode> = {
    dashboard: (
      <>
        <rect x="4" y="3" width="16" height="18" rx="4" />
        <rect x="8" y="7" width="4" height="10" rx="1" />
        <path d="M15 8v8M18 11v5" />
      </>
    ),
    users: (
      <>
        <circle cx="9" cy="8" r="4" />
        <path d="M3 21c.5-4.2 2.5-6.3 6-6.3s5.5 2.1 6 6.3M16 4.5a3.5 3.5 0 0 1 0 7M17 14c2.3.5 3.6 2.3 4 5" />
      </>
    ),
    admin: (
      <>
        <rect x="4" y="3" width="16" height="18" rx="4" />
        <circle cx="12" cy="9" r="3" />
        <path d="M7.5 18c.8-2.1 2.3-3.2 4.5-3.2s3.7 1.1 4.5 3.2" />
      </>
    ),
    squareUser: (
      <>
        <SquareUser></SquareUser>
      </>
    ),
    registrations: (
      <>
        <rect x="5" y="5" width="14" height="16" rx="4" />
        <path d="M9 5V3h6v2M9 12l2 2 4-4" />
      </>
    ),
    roles: (
      <>
        <path d="M8 4.5A4.5 4.5 0 0 0 4 9v6a4 4 0 0 0 4 4h7a5 5 0 0 0 5-5V9a4 4 0 0 0-4-4z" />
        <circle cx="9" cy="10" r="2" />
        <path d="M16 3v4h4" />
      </>
    ),
    reports: (
      <>
        <rect x="3" y="4" width="18" height="14" rx="2" />
        <path d="M8 22h8M12 18v4M7 9l3 3 3-2 4 3" />
      </>
    ),
    settings: (
      <>
        <circle cx="12" cy="12" r="3" />
        <path d="M19 13.5v-3l-2-.6a7 7 0 0 0-.7-1.7l1-1.8-2.1-2.1-1.8 1a7 7 0 0 0-1.7-.7L11 2H8l-.6 2.6a7 7 0 0 0-1.7.7l-1.8-1-2.1 2.1 1 1.8a7 7 0 0 0-.7 1.7L0 10.5v3l2.1.6a7 7 0 0 0 .7 1.7l-1 1.8 2.1 2.1 1.8-1a7 7 0 0 0 1.7.7L8 22h3l.7-2.6a7 7 0 0 0 1.7-.7l1.8 1 2.1-2.1-1-1.8a7 7 0 0 0 .7-1.7z" />
      </>
    ),
    chevron: <path d="m9 18 6-6-6-6" />,
  };

  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      fill="none"
      stroke="currentColor"
      strokeLinecap="round"
      strokeLinejoin="round"
      strokeWidth="1.7"
      aria-hidden="true"
    >
      {paths[name]}
    </svg>
  );
}


function Brand({ compact }: { compact: boolean }) {
  return (
    <Link href={'/'} className={`flex items-center ${compact ? "justify-center" : "gap-2"}`}>
       <Image className="w-[150px] px-2" src={logoImg.src} alt="sq logo" width={200} height={200}></Image>
    </Link>
  );
}

function HelpBadge() {
  return (
    <div className="relative flex size-11 shrink-0 items-center justify-center rounded-full bg-slate-100 shadow-inner">
      <div className="absolute inset-1 rounded-full border-4 border-violet-500 border-b-indigo-700 border-r-amber-400" />
      <div className="absolute size-4 rounded-full bg-white shadow-sm" />
    </div>
  );
}

function normalizePath(path: string) {
  return path.replace(/\/+$/, "") || "/";
}

function isItemActive(pathname: string, item: NavigationItem) {
  const normalizedPathname = normalizePath(pathname);
  const normalizedHref = normalizePath(item.href);

  if (normalizedHref === "/dashboard") return normalizedPathname === normalizedHref;

  const itemPath = normalizedHref.split("/").slice(0, 3).join("/");
  return normalizedPathname === itemPath || normalizedPathname.startsWith(`${itemPath}/`);
}

function isChildActive(pathname: string, href: string) {
  return normalizePath(pathname) === normalizePath(href);
}

export function DashboardSidebar({
  collapsed,
  onCollapsedChange,
}: {
  collapsed: boolean;
  onCollapsedChange: (collapsed: boolean) => void;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const { user } = useDashboardAccess();
  const visibleNavigation = getVisibleNavigation(user);
  const [loggingOut, setLoggingOut] = useState(false);
  const [error, setError] = useState("");

   async function handleLogout() {
    if (loggingOut) return;

    setLoggingOut(true);
    setError("");

    try {
      await logoutUser();
      router.replace("/signin");
      router.refresh();
    } catch (logoutError) {
      setError(
        logoutError instanceof Error
          ? logoutError.message
          : "Unable to log out. Please try again.",
      );
      setLoggingOut(false);
    }
  }

  

  return (
    <aside
      className={`sticky top-8 flex shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm transition-[width] duration-300 ${
        collapsed ? "w-20" : "w-72"
      }`}
    >
      <div className={`flex h-20 shrink-0 items-center ${collapsed ? "justify-center" : "justify-between px-4"}`}>
        <Brand compact={collapsed} />
        {!collapsed && (
          <button
            type="button"
            aria-label="Collapse sidebar"
            onClick={() => onCollapsedChange(true)}
            className="flex size-7 items-center justify-center rounded-full text-slate-600 transition hover:bg-slate-100 hover:text-violet-600 focus:outline-none focus:ring-2 focus:ring-violet-400"
          >
            <Icon name="chevron" className="size-4 rotate-180" />
          </button>
        )}
      </div>

      {collapsed && (
        <button
          type="button"
          aria-label="Expand sidebar"
          onClick={() => onCollapsedChange(false)}
          className="mx-auto mb-2 flex size-7 shrink-0 items-center justify-center rounded-full text-slate-600 transition hover:bg-slate-100 hover:text-violet-600 focus:outline-none focus:ring-2 focus:ring-violet-400"
        >
          <Icon name="chevron" className="size-4" />
        </button>
      )}

      <nav
        aria-label="Main navigation"
        className={`dashboard-scrollbar flex-1 pb-3 ${
          collapsed ? "px-3" : "px-4"
        }`}
      >
        <div className="space-y-1">
          {visibleNavigation.map((item) => {
            const active = isItemActive(pathname, item);
            return (
              <div key={item.label} className="group relative">
                <Link
                  href={item.href}
                  aria-current={active ? "page" : undefined}
                  className={`flex w-full items-center rounded-lg transition focus:outline-none focus:ring-2 focus:ring-violet-400 ${
                    collapsed
                      ? "h-11 justify-center"
                      : "min-h-11 gap-3 px-2.5 text-sm font-semibold"
                  } ${
                    active
                      ? "bg-violet-600 text-white shadow-md shadow-violet-200"
                      : "text-slate-800 hover:bg-slate-50"
                  }`}
                >
                  <Icon
                    name={item.icon}
                    className={`size-5 shrink-0 ${active ? "text-white" : "text-slate-700"}`}
                  />
                  {!collapsed && (
                    <>
                      <span className="flex-1 whitespace-nowrap">{item.label}</span>
                      {item.children && (
                        <Icon name="chevron" className="size-3 -rotate-90" />
                      )}
                    </>
                  )}
                </Link>

                {!collapsed && item.children && (
                  <div className="relative ml-5 border-l border-slate-200 py-1 pl-3">
                    {item.children.map((child) => {
                      const childActive = isChildActive(pathname, child.href);
                      return (
                        <Link
                          key={child.href}
                          href={child.href}
                          aria-current={childActive ? "page" : undefined}
                          className={`flex items-center gap-3 rounded-md px-3 py-2.5 text-xs transition ${
                            childActive
                               ? "bg-violet-50 font-semibold text-violet-700"
                               : "text-slate-600 hover:bg-slate-50 hover:text-slate-900"
                          }`}
                        >
                          <Icon
                            name={child.icon}
                            className={`size-4 shrink-0 ${
                              childActive ? "text-violet-600" : "text-slate-500"
                            }`}
                          />
                          <span className="whitespace-nowrap">{child.label}</span>
                        </Link>
                      );
                    })}
                  </div>
                )}

                {collapsed && (
                  <div className="pointer-events-none invisible absolute left-full top-1/2 z-30 ml-3 -translate-y-1/2 opacity-0 transition-all duration-150 group-hover:pointer-events-auto group-hover:visible group-hover:opacity-100">
                    <div className="absolute -left-3 top-0 h-full w-3" />
                    <div className="mb-1 w-max rounded bg-slate-900 px-2 py-1 text-xs font-semibold text-white shadow">
                      {item.label}
                    </div>
                    {item.children && (
                      <div className="w-56 rounded-lg border border-slate-100 bg-white p-2 shadow-xl">
                        {item.children.map((child) => (
                          <Link
                            key={child.href}
                            href={child.href}
                            aria-current={isChildActive(pathname, child.href) ? "page" : undefined}
                            className={`flex items-center gap-3 rounded-md px-3 py-2 text-xs transition ${
                              isChildActive(pathname, child.href)
                                ? "bg-violet-500 font-semibold text-white"
                                : "text-slate-600 hover:bg-slate-50 hover:text-slate-900"
                            }`}
                          >
                            <Icon name={child.icon} className="size-4 shrink-0" />
                            <span className="whitespace-nowrap">{child.label}</span>
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </nav>

      <div className={`shrink-0 p-4 ${collapsed ? "flex justify-center" : ""}`}>
        {collapsed ? (
          <HelpBadge />
        ) : (
          <div className="flex items-center gap-3 rounded-lg border border-slate-200 p-3">
            <HelpBadge />
            <div className="min-w-0">
              <div className="text-sm font-bold text-slate-900">Need help?</div>
              <div className="mt-1 whitespace-nowrap text-[0.65rem] text-slate-500">
                Go to Help Center <span aria-hidden="true">→</span>
              </div>
            </div>
          </div>
        )}
      </div>
      <Button onClick={handleLogout} className={`shrink-0 px-3 pb-4 cursor-pointer ${collapsed ? "flex justify-center" : ""}`}>
        {collapsed ? (
          <div className="group relative flex items-center hover:bg-slate-50 hover:text-white rounded-lg px-5 py-2.5 w-full">
            <LogOut className="hover:opacity-1 stroke-violet-500 "></LogOut>
            <span className="absolute left-full top-1/2 z-50 ml-3 -translate-y-1/2 translate-x-0 whitespace-nowrap rounded bg-slate-900 px-3 py-1 text-xs font-medium text-white invisible group-hover:visible ">Log Out</span>
          </div>
        ) : (
          <div className="flex items-center gap-3 rounded-lg border w-full border-slate-200 p-2">
            <LogOut className="w-5 stroke-violet-500"></LogOut>
            <h2 className="text-violet-500">Log Out</h2>
          </div>
        )}
      </Button>
    </aside>
  );
}
