"use client";

import Link from "next/link";
import { memo } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import { Logo } from "@/components/atoms/logo";
import type { NavigationChild, NavigationItem } from "./navigation";
import type { ComponentType, SVGProps } from "react";

// Shared navigation item styling
const navItemBaseClass =
  "group w-full flex items-center px-3 py-2.5 text-sm font-semibold rounded-lg transition-all duration-200 relative focus:outline-none focus:ring-2 focus:ring-white/30";
const activeClass = "text-white bg-white/20 shadow-sm";
const inactiveClass = "text-white/90 hover:text-white hover:bg-white/10";

function ActiveIndicator({ small = false }: { small?: boolean }) {
  const size = small ? "w-0.5 h-4" : "w-1 h-6";
  const rounded = small ? "rounded-full" : "rounded-r-full";
  return <div className={`absolute left-0 top-1/2 -translate-y-1/2 ${size} bg-white ${rounded}`} />;
}

function NavIcon({
  icon: Icon,
  isActive,
  variant = "default",
}: {
  icon: ComponentType<SVGProps<SVGSVGElement>>;
  isActive: boolean;
  variant?: "default" | "logout";
}) {
  if (variant === "logout") {
    return (
      <div className="p-1.5 rounded-md mr-3 text-red-300 group-hover:text-red-100 transition-colors duration-[var(--cp-duration-normal)]">
        <Icon className="h-5 w-5" />
      </div>
    );
  }

  return (
    <div
      className={`p-1.5 rounded-md mr-3 transition-colors duration-200 ${
        isActive ? "bg-white/20 text-white" : "text-white/80 group-hover:text-white"
      }`}
    >
      <Icon className="h-5 w-5" />
    </div>
  );
}

interface SidebarProps {
  navigation: NavigationItem[];
  pathname: string;
  expandedItems: string[];
  toggleExpanded: (name: string) => void;
  isMobile?: boolean;
}

export const Sidebar = memo(function Sidebar({
  navigation,
  pathname,
  expandedItems,
  toggleExpanded,
}: SidebarProps) {
  return (
    <div className="flex flex-col h-0 flex-1 bg-sidebar">
      <div className="flex items-center flex-shrink-0 h-16 px-5 border-b border-sidebar-border">
        <div className="flex items-center space-x-3">
          <div className="h-10 w-10 bg-white rounded-xl shadow-lg shadow-black/10 flex items-center justify-center">
            <Logo size={26} />
          </div>
          <div>
            <span className="text-base font-bold text-white">Assist Solutions</span>
            <p className="text-xs text-white/70 font-medium">Customer Portal</p>
          </div>
        </div>
      </div>

      <div className="flex-1 flex flex-col pt-6 pb-4 overflow-y-auto">
        <nav className="flex-1 px-3 space-y-1">
          {navigation.map(item => (
            <NavigationItem
              key={item.name}
              item={item}
              pathname={pathname}
              isExpanded={expandedItems.includes(item.name)}
              toggleExpanded={toggleExpanded}
            />
          ))}
        </nav>
      </div>
    </div>
  );
});

function ExpandableNavItem({
  item,
  pathname,
  isExpanded,
  toggleExpanded,
  router,
}: {
  item: NavigationItem;
  pathname: string;
  isExpanded: boolean;
  toggleExpanded: (name: string) => void;
  router: ReturnType<typeof useRouter>;
}) {
  const isActive =
    item.children?.some((child: NavigationChild) =>
      pathname.startsWith((child.href || "").split(/[?#]/)[0] ?? "")
    ) ?? false;

  return (
    <div className="relative">
      <button
        onClick={() => toggleExpanded(item.name)}
        aria-expanded={isExpanded}
        className={`${navItemBaseClass} text-left ${isActive ? activeClass : inactiveClass}`}
      >
        {isActive && <ActiveIndicator />}
        <NavIcon icon={item.icon} isActive={isActive} />
        <span className="flex-1">{item.name}</span>
        <svg
          className={`h-4 w-4 transition-transform duration-200 ease-out ${isExpanded ? "rotate-90" : ""} ${
            isActive ? "text-white" : "text-white/60 group-hover:text-white/80"
          }`}
          viewBox="0 0 20 20"
          fill="currentColor"
        >
          <path
            fillRule="evenodd"
            d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
            clipRule="evenodd"
          />
        </svg>
      </button>

      <div
        className={`overflow-hidden transition-all duration-300 ease-out ${
          isExpanded ? "max-h-96 opacity-100" : "max-h-0 opacity-0"
        }`}
      >
        <div className="mt-1 ml-6 space-y-0.5 border-l border-white/30 pl-4">
          {item.children?.map((child: NavigationChild) => {
            const isChildActive = pathname === (child.href || "").split(/[?#]/)[0];
            return (
              <Link
                key={child.href || child.name}
                href={child.href}
                prefetch
                onMouseEnter={() => child.href && void router.prefetch(child.href)}
                className={`group flex items-center px-3 py-2 text-sm rounded-md transition-all duration-200 relative ${
                  isChildActive
                    ? "text-white bg-white/20 font-semibold"
                    : "text-white/80 hover:text-white hover:bg-white/10 font-medium"
                }`}
                title={child.tooltip || child.name}
                aria-current={isChildActive ? "page" : undefined}
              >
                {isChildActive && <ActiveIndicator small />}
                <div
                  className={`w-1.5 h-1.5 rounded-full mr-3 transition-colors duration-200 ${
                    isChildActive ? "bg-white" : "bg-white/40 group-hover:bg-white/70"
                  }`}
                />
                <span className="truncate">{child.name}</span>
              </Link>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function LogoutNavItem({ item, onLogout }: { item: NavigationItem; onLogout: () => void }) {
  return (
    <button
      onClick={onLogout}
      className="group w-full flex items-center px-3 py-2.5 text-sm font-semibold text-red-300 hover:text-red-100 hover:bg-red-500/25 rounded-lg transition-colors duration-[var(--cp-duration-normal)] focus:outline-none focus:ring-2 focus:ring-red-400/30"
    >
      <NavIcon icon={item.icon} isActive={false} variant="logout" />
      <span>{item.name}</span>
    </button>
  );
}

function SimpleNavItem({
  item,
  isActive,
  router,
}: {
  item: NavigationItem;
  isActive: boolean;
  router: ReturnType<typeof useRouter>;
}) {
  return (
    <Link
      href={item.href || "#"}
      prefetch
      onMouseEnter={() => item.href && item.href !== "#" && void router.prefetch(item.href)}
      className={`${navItemBaseClass} ${isActive ? activeClass : inactiveClass}`}
      aria-current={isActive ? "page" : undefined}
    >
      {isActive && <ActiveIndicator />}
      <NavIcon icon={item.icon} isActive={isActive} />
      <span className="truncate">{item.name}</span>
    </Link>
  );
}

const NavigationItem = memo(function NavigationItem({
  item,
  pathname,
  isExpanded,
  toggleExpanded,
}: {
  item: NavigationItem;
  pathname: string;
  isExpanded: boolean;
  toggleExpanded: (name: string) => void;
}) {
  const { logout } = useAuthStore();
  const router = useRouter();

  const hasChildren = item.children && item.children.length > 0;

  if (hasChildren) {
    return (
      <ExpandableNavItem
        item={item}
        pathname={pathname}
        isExpanded={isExpanded}
        toggleExpanded={toggleExpanded}
        router={router}
      />
    );
  }

  if (item.isLogout) {
    const handleLogout = () => void logout().then(() => router.push("/"));
    return <LogoutNavItem item={item} onLogout={handleLogout} />;
  }

  const isActive = item.href ? pathname === item.href : false;
  return <SimpleNavItem item={item} isActive={isActive} router={router} />;
});
