import PropTypes from 'prop-types';
import { useLocation } from 'react-router-dom';
import { useIntl } from 'react-intl';

import { SideNav, SideNavSection, SideNavItem } from '@astryxdesign/core/SideNav';
import { Icon } from '@astryxdesign/core/Icon';

import nearle from 'menu-items/nearle';
import { DT } from 'themes/dt/tokens';

// Thin wrapper around Astryx's SideNav, driven by menu-items/nearle.js.
// Pattern (controlled collapse from the parent, section grouping, the CSS
// override block for row spacing/selected-state styling) mirrors
// doormile_crm/src/layout/MainLayout/Sidebar.jsx — that sibling app's
// Astryx sidebar is the validated reference; only the accent colour changes
// (brand red DT.brand instead of their navy) and items come from the
// existing nearle.js menu config instead of a flat navItems array.
// react-router routing works via the app-root LinkProvider (see
// src/index.js) — no per-item Link bridging needed.

const AppSideNav = ({ isCollapsed, onCollapsedChange }) => {
  const { pathname } = useLocation();
  const intl = useIntl();

  const renderMenuItem = (item) => {
    const label = intl.formatMessage({ id: item.id });
    // Wrap explicitly in Astryx's own <Icon> rather than passing the bare
    // component and letting SideNavItem's renderIconSlot auto-detect it:
    // that detection only matches plain functions/forwardRef objects, not
    // React.memo-wrapped ones (which several @ant-design/icons v5 icons
    // are) — those fell through and got returned as a raw, uninstantiated
    // element, crashing with "Objects are not valid as a React child".
    // Wrapping here always renders through Icon's own component-mode path,
    // which handles any component type and gives every icon the same
    // normalised size/colour regardless of source library.
    const icon = item.icon ? <Icon icon={item.icon} /> : undefined;

    if (item.type === 'collapse') {
      const isChildSelected = item.children.some((child) => pathname.startsWith(child.url));
      return (
        <SideNavItem key={item.id} label={label} icon={icon} collapsible={{ defaultIsCollapsed: !isChildSelected }} isSelected={isChildSelected}>
          {item.children.map(renderMenuItem)}
        </SideNavItem>
      );
    }

    return <SideNavItem key={item.id} label={label} icon={icon} href={item.url} isSelected={pathname.startsWith(item.url)} />;
  };

  return (
    <>
      <SideNav
        className="doormile-side-nav"
        collapsible={{ isCollapsed, onCollapsedChange, buttonLabel: 'Collapse navigation' }}
        style={{
          backgroundColor: DT.surface,
          borderRight: `1px solid ${DT.borderSubtle}`,
          boxShadow: '1px 0 3px rgba(15, 23, 42, 0.03)',
          paddingBlock: '12px',
          paddingInline: '8px',
          boxSizing: 'border-box',
          '--spacing-12': '72px'
          // Sticky positioning + height/scroll are already handled by
          // AppShell's own auto-mode side nav wrapper (position: sticky,
          // top/height driven by --appshell-header-height, see
          // AppTopNav.js). A second nested position: sticky here — inside
          // that wrapper's own scrollable LayoutPanel — was redundant and
          // gave the offset two independent calculations to drift apart on,
          // which is what caused the visible jump/scroll-away glitch.
        }}
      >
        <SideNavSection title="Doormile">{nearle.children.map(renderMenuItem)}</SideNavSection>
      </SideNav>
      <style>{`
        .doormile-side-nav .astryx-side-nav-section > div:last-child {
          gap: 6px !important;
        }

        .doormile-side-nav .astryx-side-nav-item[aria-label] {
          width: 40px;
          height: 40px;
          margin-inline: auto;
          padding: 0 !important;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background-color 0.15s ease;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label] > * {
          margin: 0 !important;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label] .astryx-icon {
          width: 18px !important;
          height: 18px !important;
          margin: 0 !important;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label]:hover {
          background-color: ${DT.brand}14 !important;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label]:focus-visible {
          outline: 2px solid ${DT.brand}66;
          outline-offset: 2px;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label][data-selected='selected'] {
          background-color: ${DT.brand}1f !important;
        }
        .doormile-side-nav .astryx-side-nav-item[aria-label][data-selected='selected'] .astryx-icon {
          color: ${DT.brand} !important;
        }

        .doormile-side-nav .astryx-side-nav-item:not([aria-label]) {
          position: relative;
          margin-inline: 2px;
          height: auto;
          padding-block: 12px !important;
          transition: background-color 0.15s ease, transform 0.15s ease;
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label])::before {
          content: '';
          position: absolute;
          left: -2px;
          top: 12px;
          bottom: 12px;
          width: 3px;
          border-radius: 3px;
          background-color: ${DT.brand};
          opacity: 0;
          transition: opacity 0.15s ease;
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label]):hover {
          background-color: ${DT.brand}0d !important;
          transform: translateX(2px);
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label]):focus-visible {
          outline: 2px solid ${DT.brand}66;
          outline-offset: 2px;
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label])[data-selected='selected'] {
          background-color: ${DT.brand}14 !important;
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label])[data-selected='selected']::before {
          opacity: 1;
        }
        .doormile-side-nav .astryx-side-nav-item:not([aria-label])[data-selected='selected'] .astryx-icon {
          color: ${DT.brand} !important;
        }

        .doormile-side-nav > div:last-child {
          padding-block: 8px !important;
        }

        .doormile-side-nav button[aria-label*="sidebar"],
        .doormile-side-nav button[aria-label*="navigation"] {
          border-radius: 50% !important;
          transition: background-color 0.15s ease !important;
        }
        .doormile-side-nav button[aria-label*="sidebar"]:hover,
        .doormile-side-nav button[aria-label*="navigation"]:hover {
          background-color: ${DT.brand}14 !important;
        }
      `}</style>
    </>
  );
};

AppSideNav.propTypes = {
  isCollapsed: PropTypes.bool.isRequired,
  onCollapsedChange: PropTypes.func.isRequired
};

export default AppSideNav;
