import Axios from "axios";
import { useCallback, useEffect, useState } from "react";
import { setupCache } from "axios-cache-interceptor";
import Option from "../interfaces/option";
const instance = Axios.create();
const axios = setupCache(instance);

export default function useUsersSelect(props?: {
  type?: string;
  size?: number;
  orderBy?: string;
  direction?: "asc" | "desc";
  entities?: string[] | string;
}) {
  const [inputValue, setInputValue] = useState("");
  const [users, setUsers] = useState<Option[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const onScrollLoadMoreOptions = useCallback(() => {
    if (users.length === total) return;
    const params = new URLSearchParams();

    if (!!props)
      Object.keys(props).forEach((key) => {
        if (props[key as keyof typeof props] !== undefined)
          params.append(key, props[key as keyof typeof props]!.toString());
      });
    setIsLoading(true);

    return axios
      .get<{ users: Option[]; total: number }>(
        `/api/users/search?value=${inputValue}&page=${
          page + 1
        }&${params.toString()}`,
        { headers: { page: "register" } }
      )
      .then((response) => {
        setPage((curr) => curr + 1);
        setTotal(response.data.total);
        setUsers((curr) => [...curr, ...response.data.users]);
        setIsLoading(false);
        return response.data.users;
      });
  }, [inputValue, page, props, total, users.length]);

  const loadOptions = useCallback(
    async (inputValue: string,forced?:boolean) => {
      let load = true;
      setInputValue((currValue) => {
        if (!forced&&currValue === inputValue) {
          load = false;
          return currValue;
        }
        return inputValue;
      });
      if (!load) return;
      const params = new URLSearchParams();

      if (!!props)
        Object.keys(props).forEach((key) => {
          if (props[key as keyof typeof props] !== undefined)
            params.append(key, props[key as keyof typeof props]!.toString());
        });
      setIsLoading(true);
      setPage(0);

      return axios
        .get<{ users: Option[]; total: number }>(
          `/api/users/search?value=${inputValue}&page=0&${params.toString()}`,
          { headers: { page: "register" } }
        )
        .then((response) => {
          setTotal(response.data.total);
          setUsers(response.data.users);
          setIsLoading(false);
          return response.data.users;
        });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [props?.entities, props?.type, props?.size, props?.orderBy, props?.direction]
  );

  useEffect(() => {
    loadOptions("",true);
  }, [loadOptions]);

  return {
    users,
    total,
    isLoading,
    isError,
    onScrollLoadMoreOptions,
    loadOptions,
    inputValue,
  };
}
