import {Type, User} from "@/interfaces/user";
import Axios from "axios";
import {useEffect, useState} from "react";
import {setupCache} from "axios-cache-interceptor";
const instance = Axios.create();
const axios = setupCache(instance);

export const userHashStudent = {type: "student"} as {type: Type};
export const userHashTeacher = {type: "teacher"} as {type: Type};
export const userHashCorporate = {type: "corporate"} as {type: Type};

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

	const getData = () => {
		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());
			});

		console.log(params.toString());

		setIsLoading(true);
		axios
			.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
			.then((response) => {
				setUsers(response.data.users);
				setTotal(response.data.total);
			})
			.finally(() => setIsLoading(false));
	};
	// eslint-disable-next-line react-hooks/exhaustive-deps
	useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction]);

	return {users, total, isLoading, isError, reload: getData};
}
