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

export function useField() {
  const [field, setField] = useState({
    department: '',
    type: '',
    name: '',
  });

  function onChange(key: keyof typeof field) {
    return function(value: string) {
      setField(prev => ({...prev, [key]: value}));
    };
  }

  return [field, onChange] as const;
}

export function useSearch(
  {name, type, department}: {name: string, type: string, department: string},
) {
  const dispatch = useContextSection(context, state => state[1]);

  function onSearch() {
    dispatch({type: 'SEARCH', payload: {name, department, type}});
  }

  return onSearch;
}

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

  function onExport() {
    mutate({
      page: String(page),
      limit: String(pageSize),
      containerName: name,
      type,
      department,
    });
  }

  return [isExporting, onExport] as const;
}
