import { useMountEffect } from '@react-hookz/web';
import { useEffect, useState } from 'react';

export interface Location {
  trigger: string;
  state?: any; // eslint-disable-line @typescript-eslint/no-explicit-any
  length?: number;
  hash?: string;
  host?: string;
  hostname?: string;
  href?: string;
  origin?: string;
  pathname?: string;
  port?: string;
  protocol?: string;
  search?: string;
}

const _window = typeof window !== 'undefined' ? window : undefined;

export function getLocationState(trigger: string): Location {
  const { state, length } = _window?.history || {};
  const {
    hash,
    host,
    hostname,
    href,
    origin,
    pathname,
    port,
    protocol,
    search,
  } = _window?.location || {};

  return {
    trigger,
    state,
    length,
    hash,
    host,
    hostname,
    href,
    origin,
    pathname,
    port,
    protocol,
    search,
  };
}

export function useLocation() {
  const [state, setState] = useState<Location | null>(null);

  useMountEffect(() => {
    setState(getLocationState('load'));
  });

  useEffect(() => {
    if (_window) {
      const handlePopState = () => setState(getLocationState('popstate'));
      const handleHashChange = () => setState(getLocationState('hashchange'));
      _window.addEventListener('popstate', handlePopState, { passive: true });
      _window.addEventListener('hashchange', handleHashChange, {
        passive: true,
      });
      return () => {
        _window.removeEventListener('popstate', handlePopState);
        _window.removeEventListener('hashchange', handleHashChange);
      };
    }
  }, []);

  return state;
}
