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

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

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

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

export default Filter;
