"use client";
import Link from "next/link";
import React, { useState, useEffect, memo } from "react";
import { API } from "@/app/_lib/api";
import { setOrganizationForPath } from "@/app/_lib/orgSession";

type MenuItem = {
  id: number;
  role: number;
  user_project: string;
  user_role: string;
  organization?: number;
  project_name?: string;
  project_type?: number | string;
  project_parent?: number | string;
  project_url?: string;
  project_root?: number | string;
  project_id?: number | string;
  icon?: string;
};

const ChildNavItem = memo(({ item }: { item: MenuItem }) => {
  const href = item.project_url ?? "#";

  const handleClick = () => {
    // Stash the organization in sessionStorage (keyed by destination path)
    // instead of appending it to the URL, so it never shows up in the
    // address bar, browser history, or a copied/shared link.
    const pathname = (() => {
      try {
        return new URL(href, window.location.origin).pathname;
      } catch {
        return href;
      }
    })();
    setOrganizationForPath(pathname, item.organization ?? null);
  };

  return (
    <li className="nav-item">
      <Link className="nav-link" href={href} onClick={handleClick}>
        <div className="d-flex align-items-center">
          <span className={`${item.icon} fs-9 text-body-tertiary me-2 me-lg-1 me-xl-2`}>{" "}</span>
          <span>{item.project_name}</span>
        </div>
      </Link>
    </li>
  );
});
ChildNavItem.displayName = "ChildNavItem";

const ParentNavItem = memo(({ parent, children }: { parent: MenuItem; children: MenuItem[] }) => (
  <div>
    <a
      className="nav-link dropdown-indicator label-1"
      href={`#dashboard-${parent.id}`}
      role="button"
      data-bs-toggle="collapse"
      aria-expanded="false"
      aria-controls={`dashboard-${parent.id}`}
    >
      <div className="d-flex align-items-center">
        <span className={`${parent.icon} fs-9 text-body-tertiary me-2 me-lg-1 me-xl-2`}>{" "}</span>
        <span className="nav-link-text">{parent.project_name}</span>
      </div>
    </a>
    <div className="parent-wrapper label-1">
      <ul className="nav collapse parent" data-bs-parent="#navbarVerticalCollapse" id={`dashboard-${parent.id}`}>
        {children.map((child) => <ChildNavItem key={child.id} item={child} />)}
      </ul>
    </div>
  </div>
));
ParentNavItem.displayName = "ParentNavItem";

export default function PhoenixLeftSideBar() {
  const [data,    setData]    = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // FIX: removed ?user_id=${userId} query param — the backend's user_wise_menu
    // view uses request.user.id (IDOR-safe). Passing user_id as a param allowed
    // any authenticated user to view any other user's menu by changing the value.
    API.get<MenuItem[]>("auth/api/user_wise_menu/")
      .then(({ data }) => setData(Array.isArray(data) ? data : []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const parents = data.filter(
    (m) =>
      m.project_type == 1 &&
      m.project_parent == 0 &&
      m.project_root == 0 &&
      m.role != 1
  );

  const childrenOf = (parentProjectId: number | string | undefined) =>
    data.filter((m) => m.project_type == 2 && m.project_parent == parentProjectId && m.role != 1);

  return (
    <nav className="navbar navbar-vertical navbar-expand-lg">
      <div className="collapse navbar-collapse" id="navbarVerticalCollapse">
        <div className="navbar-vertical-content">
          <ul className="navbar-nav flex-column" id="navbarVerticalNav">
            <li className="nav-item">
              <div className="nav-item-wrapper">
                {loading ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="nav-link" style={{ opacity: 0.35, pointerEvents: "none" }}>
                      <div className="bg-secondary rounded" style={{ height: "0.85rem", width: `${55 + i * 12}%` }} />
                    </div>
                  ))
                ) : (
                  parents.map((parent) => (
                    <ParentNavItem key={parent.id} parent={parent} children={childrenOf(parent.project_id)} />
                  ))
                )}
              </div>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  );
}
