import {useState} from 'react';
import {context, pageContext} from '../context';
import {exportDepartment} from '@apis';
import {useContextSection, useExportFile, usePage} from '@hooks';

export function useField() {
  const [state, setState] = useState({name: '', code: ''});

  function onChange(key: 'name' | 'code') {
    return function(val: string) {
      setState(prev => ({...prev, [key]: val}));
    };
  }

  return [state, onChange] as const;
}

export function useSearch(name: string, code: string) {
  const dispatch = useContextSection(context, state => state[1]);
  const [, {onCurrentPageChange}] = usePage(pageContext);

  function onSearch() {
    onCurrentPageChange(1);
    dispatch({type: 'SEARCH', payload: {name, code}});
  }

  return onSearch;
}

export function useExport() {
  const [{page, pageSize}] = usePage(pageContext);
  const [isExporting, mutate] = useExportFile(exportDepartment);
  const {code, name} = useContextSection(context, state => state[0]);

  function onExport() {
    mutate({
      page: page.toString(),
      limit: pageSize.toString(),
      code,
      departmentName: name,
    });
  }

  return [isExporting, onExport] as const;
}
