import { ToolbarCollectionBaseProps } from '../components/ToolbarCollection';
import { FiltersMap } from '@wix/bex-core';
import { isValidElement, ReactElement, ReactNode } from 'react';
import { FilterValueTotalStateParams } from './FilterValueTotalState';
import { TabTotalReactElementLike } from '../components/TabTotal/TabTotalComponentType';
import { TabsFilterProps } from '../components/TabsFilter';

function isTabTotalElement<T, F extends FiltersMap, V>(
  node: ReactNode,
): node is ReactElement<FilterValueTotalStateParams<T, F, V>> &
  TabTotalReactElementLike {
  return (
    isValidElement(node) &&
    typeof (node as Partial<TabTotalReactElementLike>).type?.initTabTotal ===
      'function'
  );
}

function isTabsFilterElement(
  node: ReactNode,
): node is ReactElement<TabsFilterProps<any>> {
  return (
    isValidElement(node) &&
    Array.isArray(node.props.data) &&
    typeof node.props.counterBadge === 'function'
  );
}

export function getToolbarCollectionFeaturesInitializers<
  T,
  F extends FiltersMap,
>(props: ToolbarCollectionBaseProps<T, F>) {
  const { tabs } = props;

  const tabTotalFeatureInitializer = (() => {
    if (isTabsFilterElement(tabs)) {
      const tabsProps = tabs.props;
      const el = tabsProps?.data
        .map((value) => tabs.props.counterBadge?.(value))
        .find(isTabTotalElement);
      return el?.type?.initTabTotal?.(tabs.props, el.props);
    }

    return undefined;
  })();

  return [tabTotalFeatureInitializer];
}
