import { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";

export function useWindowArea() {
  const [windowLength, setWindowLength] = useState(window.innerWidth);
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);

  useEffect(() => {
    const onModified = () => {
      setWindowLength(window.innerWidth);
      setWindowHeight(window.innerHeight);
    };

    window.addEventListener("resize", onModified);

    return () => {
      window.removeEventListener("resize", onModified);
    };
  }, []);

  return { windowLength, windowHeight };
}

export function useTo() {
  const navigate = useNavigate();

  return (pathname: string, search: string = window.location.search) =>
    navigate({ ...window.location, pathname, search });
}

export function useParam(text: string, defaultValue: string) {
  const [searchParams, setSearchParams] = useSearchParams();
  const param = searchParams.get(text) ?? defaultValue;

  return {
    param,
    setParam: useCallback(
      (param: string) => {
        searchParams.set(text, param.toString());
        setSearchParams(searchParams);
      },
      [searchParams, setSearchParams],
    ),
  };
}

export function useIntParam(text: string, defaultValue: number) {
  const { param, setParam } = useParam(text, defaultValue.toString());

  return {
    param: Number(param),
    setParam: useCallback(
      (param: number) => {
        setParam(param.toString());
      },
      [setParam],
    ),
  };
}

export function useWant(route: string) {
  const to = useTo();
  const { want = "" } = useParams<{ want: string }>();

  return {
    want,
    setWant: useCallback(
      (want: string) => {
        to(route + "/" + want);
      },
      [to, route],
    ),
  };
}
