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

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

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

  return [state, onChange] as const;
}

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

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

  return onSearch;
}

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

  function onExport() {
    mutate({
      page: String(page),
      limit: String(pageSize),
      userName: name,
      code,
    });
  }

  return [isExporting, onExport] as const;
}
