import React, { Dispatch, SetStateAction, useContext, useMemo } from 'react';
import { ApolloColumnType, SelectedView, Ordering } from '../../interfaces';
import Tabs from '../../../tabs';
import defaultLocale from '../../../locale/en_US';
import ConfigProvider from '../../../config-provider';
import { localFilterToComponent } from '../../utils/localFilterToComponent';

interface SelectedViewTabsProps<T> {
  allSelectedViews: SelectedView[];
  setQueryValue: Dispatch<SetStateAction<string>>;
  setSortValue: Dispatch<SetStateAction<string>>;
  setFilterValues: Dispatch<Record<string, any>>;
  activeKey: string;
  setActiveKey: Dispatch<SetStateAction<string>>;
  defaultSortValue?: Ordering;
  columns: ApolloColumnType<T>[];
}

export const SelectedViewTabs = <T extends {}>({
  activeKey,
  setActiveKey,
  setQueryValue,
  setSortValue,
  setFilterValues,
  defaultSortValue,
  allSelectedViews: propsAllSelectedViews,
  columns,
}: SelectedViewTabsProps<T>) => {
  const {
    getPrefixCls,
    locale: { ApolloTable: locale } = { ApolloTable: defaultLocale.ApolloTable },
  } = useContext(ConfigProvider.ConfigContext);

  const allSelectedViews = useMemo(
    () => propsAllSelectedViews.filter(item => item.id !== 'all'),
    [propsAllSelectedViews],
  );

  const defaultLabel = propsAllSelectedViews.find(item => item.id === 'all')?.name;

  return (
    <Tabs
      activeKey={activeKey}
      className={`${getPrefixCls('apollo-table-selected-views-tabs')}`}
      onChange={_activeKey => {
        setActiveKey(_activeKey);

        // 如果切换到 all 设置默认，否则设置配置上的值
        if (_activeKey === 'all') {
          setQueryValue('');
          setSortValue(
            defaultSortValue ? `${defaultSortValue.field} ${defaultSortValue.direction}` : '',
          );
          setFilterValues({});
        } else {
          const current = allSelectedViews.find(item => item.id === _activeKey);
          setQueryValue(current?.query || '');
          setSortValue(
            current?.orderBy ? `${current.orderBy.field} ${current.orderBy.direction}` : '',
          );

          // 本地的
          if (_activeKey.startsWith('savedSearch')) {
            setFilterValues(localFilterToComponent(current?.filters || {}, columns));
            // 配置的或服务端的
          } else {
            setFilterValues(current?.filters || {});
          }
        }
      }}
    >
      <Tabs.TabPane key="all" tab={defaultLabel || locale?.all} />
      {allSelectedViews.map(item => (
        <Tabs.TabPane key={item.id} tab={item.name} />
      ))}
    </Tabs>
  );
};
