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

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

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

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

export default Filter;
