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 = "") =>
    navigate({ ...window.location, pathname, search });
}

export function usePage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const page = Number(searchParams.get("page") ?? "1");

  return {
    page,
    setPage: useCallback(
      (page: number) => {
        searchParams.set("page", page.toString());
        setSearchParams(searchParams);
      },
      [searchParams, setSearchParams],
    ),
  };
}

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

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