import {
  Accordion,
  SidePanel,
  SidePanelProps,
  WixStyleReactDefaultsOverrideProvider,
} from '@wix/design-system';
import React, { useState } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { useBuildAccordionItems } from '../../hooks/useBuildAccordionItems';
import { FiltersPanelFooter } from './FiltersPanelFooter';
import { FilterRenderingContextProvider } from '../FilterRenderingContext';
import { FiltersPanelState } from './FiltersPanelState';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useRafRender } from '../../hooks/useRafRender';
import { CollectionToolbarFiltersState } from '../CollectionToolbarFilters/CollectionToolbarFiltersState';

export interface FiltersPanelProps<T, F extends FiltersMap>
  extends Partial<SidePanelProps> {
  state: CollectionToolbarFiltersState<T, F>;
}

function _FiltersPanel<T, F extends FiltersMap>(
  props: FiltersPanelProps<T, F>,
) {
  const { state, children, ...rest } = props;

  const {
    toolbar,
    totalInlineFilters: { value: totalInlineFilters },
  } = state;

  const accordionItems = useBuildAccordionItems(state);

  const entered = useRafRender();

  const { translate: t } = useWixPatternsContainer();

  const [filtersPanelState] = useState(
    () =>
      new FiltersPanelState({
        toolbar,
      }),
  );

  const [filterRenderingContext] = useState(() => ({
    location: 'panel' as const,
  }));

  const [wsrDefaults] = useState(() => ({
    input: {
      size: 'small' as const,
    },
    button: {
      size: 'small' as const,
    },
  }));

  if (!entered) {
    return null;
  }

  let child = (
    <SidePanel
      dataHook="filters-side-panel"
      onCloseButtonClick={filtersPanelState.onCloseButtonClick}
      width="100%"
      {...rest}
    >
      <SidePanel.Header
        title={
          state.panelTitle.value ??
          (totalInlineFilters != null
            ? t('cairo.filtersPanel.header', {
                num: totalInlineFilters,
              })
            : undefined)
        }
      />

      <div
        data-hook="filters-panel-scroll-container"
        style={{ overflowY: 'auto' }}
      >
        <Accordion
          dataHook="filters-panel-accordion"
          skin="light"
          hideShadow
          multiple
          items={accordionItems}
        />
      </div>
      <SidePanel.Footer noPadding>
        <FiltersPanelFooter
          state={toolbar}
          onClearButtonClicked={state.onClearButtonClicked}
        />
      </SidePanel.Footer>
      {children}
    </SidePanel>
  );

  child = (
    <FilterRenderingContextProvider value={filterRenderingContext}>
      {child}
    </FilterRenderingContextProvider>
  );

  child = (
    <WixStyleReactDefaultsOverrideProvider value={wsrDefaults}>
      {child}
    </WixStyleReactDefaultsOverrideProvider>
  );

  return child;
}

export const FiltersPanel = observer(_FiltersPanel);
