import {
  useContextSection,
  useFilterDB,
  useFilterField,
  useRangeDate,
  useTableSearchToolEvents,
} from '@hooks';
import {FC} from 'react';
import {context, contextState, searchContext} from '../context';
import {FilterSelectorModal, FilterTool} from '@components';
import {fixedMap, sourceMap} from './state';

const Filter: FC = function () {
  const [fields, {onChange, resetState}] = useFilterField(
    {
      ...contextState,
    },
    true,
  );
  const [{dates, start, end}, onDatesChange] = useRangeDate();
  const [visible, {onShowModal, onCloseModal, onSearch, onReset}] =
    useTableSearchToolEvents(
      context,
      {
        ...fields,
        startTime: start,
        endTime: end,
      },
      {
        resetCallback() {
          resetState();
          onDatesChange([null, null]);
        },
      },
    );
  const isSearching = useContextSection(
    searchContext,
    state => state[0].isSearching,
  );
  const [filterList, {set}] = useFilterDB();

  return (
    <>
      <FilterTool
        testId='deliver_trace_search_tool'
        fields={fields}
        dates={dates}
        onChange={onChange}
        onDatesChange={onDatesChange}
        onReset={onReset}
        isSearching={isSearching}
        onSearch={onSearch}
        onFilter={onShowModal}
        fixedMap={fixedMap}
        sourceMap={sourceMap}
        filterData={filterList}
      />

      <FilterSelectorModal
        onConfirm={set}
        filtermap={sourceMap}
        source={filterList}
        onClose={onCloseModal}
        visible={visible}
      />
    </>
  );
};

export default Filter;
