import { useState, useEffect, useCallback } from 'react';
import setUrlState from './setUrlState';
import getUrlState from './getUrlState';
const useUrlState = function useUrlState(opts = {}) {
  const {
    defaults,
    stateMode = 'query'
  } = opts;
  const [isLoaded, setIsLoaded] = useState(false);
  const [data, setData] = useState(defaults || {});
  useEffect(() => {
    setIsLoaded(true);
    const state = getUrlState({
      stateMode
    });
    setData(setUrlState({
      state: {
        ...defaults,
        ...state
      },
      stateMode
    }));
  }, [defaults, stateMode]);
  const set = useCallback((key, value) => {
    if (!isLoaded) {
      throw new Error('cannot set URL state during initial render');
    }
    setData(setUrlState({
      state: {
        [key]: value
      },
      stateMode
    }));
  }, [stateMode, isLoaded]);
  const setAll = useCallback(newState => {
    if (!isLoaded) {
      throw new Error('cannot set URL state during initial render');
    }
    setData(setUrlState({
      state: newState,
      stateMode
    }));
  }, [stateMode, isLoaded]);
  useEffect(() => {
    if (stateMode !== 'hash') return undefined;
    const updateFromHash = () => {
      setData(getUrlState({
        stateMode
      }));
    };
    window.addEventListener('hashchange', updateFromHash);
    return () => {
      window.removeEventListener('hashchange', updateFromHash);
    };
  }, [stateMode]);
  return {
    isLoaded,
    data,
    set,
    setAll
  };
};
export default useUrlState;