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

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

  function onChange(val: string) {
    setState(val);
  }

  return [state, onChange] as const;
}

export function useSearch(value: string) {
  const [, dispatch] = useContext(context);
  const [, {onCurrentPageChange}] = usePage(pageContext);

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

  return onSearch;
}

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

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

  return [isExporting, onExport] as const;
}
