import { useLocale } from "next-intl";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { stringify } from "querystring";
import { useCallback, useEffect, useState } from "react";

export function useWindowArea() {
  const [windowLength, setWindowLength] = useState(
    typeof window === "object" ? window.innerWidth : 0,
  );
  const [windowHeight, setWindowHeight] = useState(
    typeof window === "object" ? window.innerHeight : 0,
  );

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

    window.addEventListener("resize", onModified);

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

  return { windowLength, windowHeight };
}

export function useParam(valueID: string, defaultValue: string) {
  const { push } = useRouter();
  const searchParams = useSearchParams();
  const value = searchParams.get(valueID) ?? defaultValue;

  const pathname = usePathname();

  return {
    param: value,
    setParam: useCallback(
      (value: string) => {
        const data: Record<string, string> = {};
        for (const searchParam of searchParams.entries()) {
          data[searchParam[0]] = searchParam[1];
        }
        push(`${pathname}?${stringify({ ...data, [valueID]: value })}`);
      },
      [pathname, push, searchParams, valueID],
    ),
  };
}

export function useIntParam(valueID: string, defaultValue: number) {
  const { push } = useRouter();
  const searchParams = useSearchParams();
  const value = Number.parseInt(
    searchParams.get(valueID) ?? defaultValue.toString(),
  );

  const pathname = usePathname();

  return {
    param: value,
    setParam: useCallback(
      (value: number) => {
        const data: Record<string, string> = {};
        for (const searchParam of searchParams.entries()) {
          data[searchParam[0]] = searchParam[1];
        }
        push(`${pathname}?${stringify({ ...data, [valueID]: value })}`);
      },
      [pathname, push, searchParams, valueID],
    ),
  };
}

export function useIsPath() {
  const pathname = usePathname();
  const locale = useLocale();

  return useCallback(
    (route: string, equals = false) => {
      const routeLanguage = `/${locale}${route}`;
      return equals
        ? pathname === routeLanguage
        : pathname.startsWith(routeLanguage);
    },
    [locale, pathname],
  );
}
