"use client";

import Link from "next/link";
import { memo } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
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-200">
        <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 SidebarUserInfo {
  firstName?: string | null | undefined;
  lastName?: string | null | undefined;
  email?: string | null | undefined;
}

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

function getSidebarDisplayName(
  user: SidebarUserInfo | null | undefined,
  profileReady: boolean
): string {
  const fullName = [user?.firstName, user?.lastName].filter(Boolean).join(" ");
  const emailPrefix = user?.email?.split("@")[0];
  if (profileReady) return fullName || emailPrefix || "Account";
  return emailPrefix || "Account";
}

function getSidebarInitials(
  user: SidebarUserInfo | null | undefined,
  profileReady: boolean,
  displayName: string
): string {
  if (profileReady && user?.firstName && user?.lastName) {
    return `${user.firstName[0]}${user.lastName[0]}`.toUpperCase();
  }
  return displayName.slice(0, 2).toUpperCase();
}

function SidebarProfile({
  user,
  profileReady,
}: {
  user?: SidebarUserInfo | null | undefined;
  profileReady: boolean;
}) {
  const displayName = getSidebarDisplayName(user, profileReady);
  const initials = getSidebarInitials(user, profileReady, displayName);

  return (
    <div className="px-3 py-3">
      <Link
        href="/account/settings"
        prefetch
        className="flex items-center gap-2.5 px-2 py-2 rounded-lg bg-white/10 hover:bg-white/15 transition-colors group"
      >
        <div className="h-7 w-7 rounded-lg bg-white/20 flex items-center justify-center text-[11px] font-bold text-white flex-shrink-0">
          {initials}
        </div>
        <span className="text-sm font-medium text-white/90 truncate group-hover:text-white transition-colors">
          {displayName}
        </span>
      </Link>
    </div>
  );
}

export const Sidebar = memo(function Sidebar({
  navigation,
  pathname,
  expandedItems,
  toggleExpanded,
  user,
  profileReady = false,
}: 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 pb-4 overflow-y-auto">
        <nav className="flex-1 px-3 pt-4 space-y-1">
          {navigation
            .filter(item => !item.isLogout)
            .map(item => (
              <div key={item.name}>
                <NavigationItem
                  item={item}
                  pathname={pathname}
                  isExpanded={expandedItems.includes(item.name)}
                  toggleExpanded={toggleExpanded}
                />
              </div>
            ))}
        </nav>
        <SidebarProfile user={user} profileReady={profileReady} />
        {navigation
          .filter(item => item.isLogout)
          .map(item => (
            <NavigationItem
              key={item.name}
              item={item}
              pathname={pathname}
              isExpanded={false}
              toggleExpanded={toggleExpanded}
            />
          ))}
      </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>
        <motion.div animate={{ rotate: isExpanded ? 90 : 0 }} transition={{ duration: 0.2 }}>
          <svg
            className={`h-4 w-4 ${
              isActive ? "text-white" : "text-white/70 group-hover:text-white"
            }`}
            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>
        </motion.div>
      </button>

      <AnimatePresence initial={false}>
        {isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
            style={{ overflow: "hidden" }}
          >
            <div className="mt-0.5 ml-[30px] space-y-0.5 border-l border-white/15 pl-3">
              {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-2.5 py-1.5 text-sm rounded-md transition-all duration-200 relative ${
                      isChildActive
                        ? "text-white bg-white/15 font-medium"
                        : "text-white/70 hover:text-white hover:bg-white/10 font-normal"
                    }`}
                    title={child.tooltip || child.name}
                    aria-current={isChildActive ? "page" : undefined}
                  >
                    {isChildActive && <ActiveIndicator small />}
                    <span className="truncate">{child.name}</span>
                  </Link>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function LogoutNavItem({ item, onLogout }: { item: NavigationItem; onLogout: () => void }) {
  return (
    <div className="px-3 pt-4 mt-2 border-t border-white/10">
      <button
        onClick={onLogout}
        className="group w-full flex items-center px-3 py-2.5 text-sm font-medium text-red-300 hover:text-red-100 hover:bg-red-500/15 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-red-400/20"
      >
        <NavIcon icon={item.icon} isActive={false} variant="logout" />
        <span>{item.name}</span>
      </button>
    </div>
  );
}

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 = (() => {
    if (!item.href) return false;
    if (item.href === "/account") return pathname === item.href;
    return pathname.startsWith(item.href);
  })();
  return <SimpleNavItem item={item} isActive={isActive} router={router} />;
});
