import React, { useEffect, useRef, useState } from 'react';
import {
  Box,
  DropdownProps,
  Input,
  listItemSelectBuilder,
} from '@wix/design-system';
import { Filter } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { TabsFilterState } from './TabsFilterState';
import { TabTotalDropdownOption } from '../TabTotal';
import { ALL_TAB_ITEM_ID, TabsFilterItem, TabsFilterItemBase } from './types';
import { SingleSelectFilterBase } from '../SingleSelectFilterBase';
import { useDropdownSelectFilterState } from '../../hooks';

export interface TabsFilterProps<V> {
  items: TabsFilterItemBase[];
  data: V[];
  filter: Filter<V[]>;
  selectedId: string;
  popoverProps?: DropdownProps['popoverProps'];
}

function _TabsDropdown<V>(props: TabsFilterProps<V>) {
  const { data: dataProp, items, filter, selectedId, popoverProps } = props;

  const { itemKey } = filter;

  const table = useToolbarCollectionContext();

  const container = useRef<HTMLDivElement>();

  const [state] = useState(
    () =>
      new TabsFilterState({
        table,
      }),
  );

  useEffect(
    () =>
      state.init({
        container: container.current,
        itemsCount: items.length,
      }),
    [],
  );

  const { isLoading, isIdle } = table.initTask.status;
  const hideCounterBadge = isLoading || isIdle;

  const options = React.useMemo(
    () =>
      items.map((item) =>
        listItemSelectBuilder({
          id: item.id,
          title: item.name,
          label: item.name,
          suffix: hideCounterBadge ? undefined : (
            <TabTotalDropdownOption
              value={dataProp.find((data) => itemKey(data) === item.id)}
            />
          ),
        }),
      ),
    [items, hideCounterBadge],
  );

  const { dropdownSelect, init } = useDropdownSelectFilterState<V>({
    filter,
  });

  useEffect(() => init(), []);

  return (
    <Box minWidth={140} maxWidth={200} paddingLeft="24px">
      <SingleSelectFilterBase
        dataHook="tabs-dropdown"
        filter={filter}
        dropdownSelect={dropdownSelect}
        options={options}
        disabled={!options.length}
        selectedId={selectedId}
        onSelect={(option) => {
          const tab = items.find((item) => item.id === option.id);

          if (tab) {
            const values =
              tab.id === ALL_TAB_ITEM_ID
                ? []
                : [(tab as TabsFilterItem<V>).value];

            filter.refresh(values);
          }
        }}
        suffix={
          hideCounterBadge ? undefined : (
            <Input.Affix>
              <TabTotalDropdownOption
                key={selectedId}
                value={dataProp.find((value) => itemKey(value) === selectedId)}
              />
            </Input.Affix>
          )
        }
        popoverProps={popoverProps}
      />
    </Box>
  );
}

export const TabsDropdown = observer(_TabsDropdown);
