"use client";

import { useEffect, useState } from "react";
import {
  getCapsearchNavigationItems,
  type SidebarNavigationItem,
} from "../lib/capsearchNavigation";

type SidebarNavigationProps = {
  currentPath: "/" | "/requests";
};

export function SidebarNavigation({ currentPath }: SidebarNavigationProps) {
  const [remoteItems, setRemoteItems] = useState<SidebarNavigationItem[]>([]);

  useEffect(() => {
    let ignore = false;

    const loadNavigation = async () => {
      const items = await getCapsearchNavigationItems();
      if (!ignore) {
        setRemoteItems(items);
      }
    };

    void loadNavigation();

    const onSessionUpdated = () => {
      void loadNavigation();
    };
    window.addEventListener("capsearch-session-updated", onSessionUpdated);

    return () => {
      ignore = true;
      window.removeEventListener("capsearch-session-updated", onSessionUpdated);
    };
  }, []);

  const navigationItems = remoteItems.map((item) => ({
    key: `remote:${item.label}:${item.href}`,
    label: item.label,
    iconClass: item.iconClass,
    href: item.href,
    active: isNavigationItemActive(item.href, currentPath),
  }));

  return (
    <nav aria-label="Primary">
      <ul>
        {navigationItems.map(({ label, iconClass, active, href, key }) => (
          <li key={key}>
            <a
              href={href}
              className={`flex h-[50px] w-full items-center gap-[16px] pl-[14px] pr-3 text-left text-[15px] font-normal leading-none transition ${
                active
                  ? "border-l-[10px] border-[#3fc3a8] bg-[#f9f9f9] text-[#3fc3a8]"
                  : "border-l-[10px] border-transparent bg-[#ebebeb] text-[#000000] hover:text-[#3fc3a8]"
              }`}
            >
              <span
                className={`flex h-[24px] w-[24px] items-center justify-center ${
                  active ? "text-[#3fc3a8]" : "text-[#000000]"
                }`}
              >
                <i aria-hidden="true" className={`${iconClass} text-[18px] leading-none`} />
              </span>
              <span className="pt-px">{label}</span>
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}

type RenderNavigationItem = {
  key: string;
  label: string;
  iconClass: string;
  href: string;
  active: boolean;
};

function isNavigationItemActive(
  href: string,
  currentPath: SidebarNavigationProps["currentPath"],
) {
  const pathname = getPathname(href);
  return pathname === currentPath;
}

function getPathname(href: string) {
  try {
    return new URL(href).pathname || "/";
  } catch {
    return href;
  }
}
