import { Children, useEffect, useState } from 'react';

import { useUrlSearchParams } from 'hooks/useUrlSearchParams';

import { Sidebar } from 'components/sidebar/Sidebar';

import { AllianceAnalyticsNavigation } from './analytics/AllianceAnalyticsNavigation';
import { AllianceFiltersPanel } from './analytics/AllianceFiltersPanel';
import { AllianceNavigation } from './AllianceNavigation';
import { PATHS as ALLIANCE_PAGE } from './index';

export const ANALYTICS_NAVIGATION_KEY = 'list';

const SidebarPanels = ({
  current,
  children,
}: {
  current: string;
  children: React.ReactNode;
}) => {
  const section = Children.toArray(children).find(
    (child) => (child as React.ReactElement).key === `.$${current}`
  );

  return section ? (section as JSX.Element) : null;
};

const DEFAULT = 'default';

export const AllianceSidebar = () => {
  const {
    [ANALYTICS_NAVIGATION_KEY]: showCollections,
    [ALLIANCE_PAGE.filter]: showFilters,
  } = useUrlSearchParams();

  const [section, setSection] = useState(DEFAULT);
  useEffect(() => {
    const collectionsPanel =
      Boolean(showCollections) && ANALYTICS_NAVIGATION_KEY;
    const filtersPanel = Boolean(showFilters) && ALLIANCE_PAGE.filter;
    const next = filtersPanel || collectionsPanel || DEFAULT;
    if (section !== next) {
      setSection(next);
    }
  }, [section, showCollections, showFilters]);

  return (
    <Sidebar>
      <SidebarPanels current={section}>
        <AllianceNavigation key={DEFAULT} />
        <AllianceAnalyticsNavigation key={ANALYTICS_NAVIGATION_KEY} />
        <AllianceFiltersPanel key={ALLIANCE_PAGE.filter} />
      </SidebarPanels>
    </Sidebar>
  );
};
