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

const Filter: FC = function () {
  const [{dates, start, end}, onDatesChange] = useRangeDate();
  const [fields, {onChange, resetState}] = useFilterField(
    {
      wllbCode: '',
      startTime: '',
      endTime: '',
      materialName: '',
      storageCode: '',
      userName: '',
      wbs: '',
      attribute: '',
      storageLocationName: '',
      realName: '',
      productionCode: '',
      companyNumber: '',
    },
    true,
  );
  const {isSearching} = useContextSection(searchContext, state => state[0]);
  const [filterList, {set}] = useFilterDB();
  const [visible, {onCloseModal, onSearch, onShowModal, onReset}] =
    useTableSearchToolEvents(
      context,
      {...fields, startTime: start, endTime: end},
      {
        resetCallback() {
          resetState();
          onDatesChange([null, null]);
        },
      },
    );

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

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

export default Filter;
