import React from 'react';
import { Tabs } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { Filter, FiltersMap } from '@wix/bex-core';
import { ALL_TAB_ITEM_ID, TabsFilterItem, TabsFilterItemBase } from './types';
import { TabsFilterState } from './TabsFilterState';

export interface TabsDefaultProps<V, T, F extends FiltersMap> {
  items: TabsFilterItemBase[];
  data: V[];
  filter: Filter<V[]>;
  selectedId: string;
  state: TabsFilterState<T, F>;
  type?: 'uniformFull';
  onChange?: (value: V | null | undefined) => unknown;
  all?: string | null | false;
}

function _TabsDefault<V, T, F extends FiltersMap>(
  props: TabsDefaultProps<V, T, F>,
) {
  const { state, filter, selectedId, items, type, onChange, all } = props;
  const { itemKey } = filter;

  const { responsive } = state;

  return (
    <Tabs
      minWidth={responsive.panelMinWidth}
      dataHook="tabs-default"
      activeId={selectedId}
      onClick={(tab) => {
        const { id } = tab as TabsFilterItemBase;
        const activeId = filter.isEmpty
          ? ALL_TAB_ITEM_ID
          : itemKey(filter.value[0]);
        const prevTab = items.find((item) => item.id === activeId);

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

        state._reportTabSelectedBiOnNextResult({
          prevTab,
          nextTab: tab as TabsFilterItemBase,
          items,
          hasAllTab: all != null,
        });
        onChange?.(values[0]);
        filter.refresh(values);
      }}
      type={type}
      items={items}
      hasDivider={false}
    />
  );
}

export const TabsDefault = observer(_TabsDefault);
