"use client";

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

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-[var(--cp-sidebar-bg)]">
      <div className="flex items-center flex-shrink-0 h-16 px-6 border-b border-[var(--cp-sidebar-border)]">
        <div className="flex items-center space-x-3">
          <div className="p-2 bg-white rounded-xl border border-[var(--cp-sidebar-border)] shadow-sm">
            <Logo size={20} />
          </div>
          <div>
            <span className="text-base font-bold text-[var(--cp-sidebar-text)]">
              Assist Solutions
            </span>
            <p className="text-xs text-[var(--cp-sidebar-text)]/60">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>
  );
});

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;
  const isActive = hasChildren
    ? item.children?.some((child: NavigationChild) =>
        pathname.startsWith((child.href || "").split(/[?#]/)[0])
      ) || false
    : item.href
      ? pathname === item.href
      : false;

  const handleLogout = () => {
    void logout().then(() => {
      router.push("/");
    });
  };

  if (hasChildren) {
    return (
      <div className="relative">
        <button
          onClick={() => toggleExpanded(item.name)}
          aria-expanded={isExpanded}
          className={`group w-full flex items-center px-3 py-2.5 text-left text-sm font-medium rounded-lg transition-all duration-200 relative ${
            isActive
              ? "text-[var(--cp-sidebar-active-text)] bg-[var(--cp-sidebar-active-bg)]"
              : "text-[var(--cp-sidebar-text)] hover:text-[var(--cp-sidebar-text-hover)] hover:bg-[var(--cp-sidebar-hover-bg)]"
          } focus:outline-none focus:ring-2 focus:ring-primary/20`}
        >
          {isActive && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-primary rounded-r-full" />
          )}

          <div
            className={`p-1.5 rounded-md mr-3 transition-colors duration-200 ${
              isActive
                ? "bg-primary/10 text-primary"
                : "text-[var(--cp-sidebar-text)]/70 group-hover:text-[var(--cp-sidebar-text-hover)] group-hover:bg-gray-100"
            }`}
          >
            <item.icon className="h-5 w-5" />
          </div>

          <span className="flex-1 font-medium">{item.name}</span>

          <svg
            className={`h-4 w-4 transition-transform duration-200 ease-out ${
              isExpanded ? "rotate-90" : ""
            } ${isActive ? "text-primary" : "text-[var(--cp-sidebar-text)]/50"}`}
            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-[var(--cp-sidebar-border)] 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={() => {
                    if (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-[var(--cp-sidebar-active-text)] bg-[var(--cp-sidebar-active-bg)] font-medium"
                      : "text-[var(--cp-sidebar-text)]/80 hover:text-[var(--cp-sidebar-text-hover)] hover:bg-[var(--cp-sidebar-hover-bg)]"
                  }`}
                  title={child.tooltip || child.name}
                  aria-current={isChildActive ? "page" : undefined}
                >
                  {isChildActive && (
                    <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 bg-primary rounded-full" />
                  )}

                  <div
                    className={`w-1.5 h-1.5 rounded-full mr-3 transition-colors duration-200 ${
                      isChildActive
                        ? "bg-primary"
                        : "bg-[var(--cp-sidebar-text)]/30 group-hover:bg-[var(--cp-sidebar-text)]/50"
                    }`}
                  />

                  <span className="truncate">{child.name}</span>
                </Link>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  if (item.isLogout) {
    return (
      <button
        onClick={handleLogout}
        className="group w-full flex items-center px-3 py-2.5 text-sm font-medium text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-red-200"
      >
        <div className="p-1.5 rounded-md mr-3 text-red-500 group-hover:text-red-600 group-hover:bg-red-100 transition-colors duration-200">
          <item.icon className="h-5 w-5" />
        </div>
        <span>{item.name}</span>
      </button>
    );
  }

  return (
    <Link
      href={item.href || "#"}
      prefetch
      onMouseEnter={() => {
        if (item.href && item.href !== "#") {
          void router.prefetch(item.href);
        }
      }}
      className={`group w-full flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-all duration-200 relative ${
        isActive
          ? "text-[var(--cp-sidebar-active-text)] bg-[var(--cp-sidebar-active-bg)]"
          : "text-[var(--cp-sidebar-text)] hover:text-[var(--cp-sidebar-text-hover)] hover:bg-[var(--cp-sidebar-hover-bg)]"
      } focus:outline-none focus:ring-2 focus:ring-primary/20`}
      aria-current={isActive ? "page" : undefined}
    >
      {isActive && (
        <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-primary rounded-r-full" />
      )}

      <div
        className={`p-1.5 rounded-md mr-3 transition-colors duration-200 ${
          isActive
            ? "bg-primary/10 text-primary"
            : "text-[var(--cp-sidebar-text)]/70 group-hover:text-[var(--cp-sidebar-text-hover)] group-hover:bg-gray-100"
        }`}
      >
        <item.icon className="h-5 w-5" />
      </div>

      <span className="truncate">{item.name}</span>
    </Link>
  );
});
