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

const Filter: FC = function () {
  const [fields, {onChange, resetState}] = useFilterField(
    {
      partType: '半成品' as const,
      productionCode: '',
      type: '',
      askGoodsCode: '',
      materialCode: '',
      materialName: '',
      departmentCode: '',
      companyCode: '',
      entryNumber: '',
      moveType: '',
      sourceType: '',
      startTime: '',
      endTime: '',
    },
    true,
  );
  const [{dates, start, end}, onDatesChange] = useRangeDate();
  const {isSearching} = useContextSection(searchContext, state => state[0]);
  const [visible, {onSearch, onReset, onShowModal, onCloseModal}] =
    useTableSearchToolEvents(
      context,
      {...fields, startTime: start, endTime: end},
      {
        resetCallback() {
          resetState();
          onDatesChange([null, null]);
        },
      },
    );
  const [filterList, {set}] = useFilterDB();

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

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

export default Filter;
