import {useState} from 'react';
import {useContextSelector} from 'use-context-selector';
import {context, pageContext} from '../context';
import {useExportFile, usePage} from '@hooks';
import {exportStorage} from '@apis';

export function useField() {
  const [fields, setFields] = useState({
    name: '',
    code: '',
    type: '',
    isNotDisable: '',
  });

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

  return [fields, onChange] as const;
}

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

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

  return onSearch;
}

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

  function onExport() {
    mutate({
      page: String(page),
      limit: String(pageSize),
      storageLocationName: name,
      storageLocationCode: code,
      storageLocationType: type,
      isNotDisable,
    });
  }

  return [isExporting, onExport] as const;
}
