import {Group, User} from "@/interfaces/user";
import Axios from "axios";
import {setupCache} from "axios-cache-interceptor";
import {useEffect, useState} from "react";

const instance = Axios.create();
const axios = setupCache(instance);

interface Props {
	admin?: string;
	userType?: string;
	adminAdmins?: string;
}

export default function useGroups({admin, userType, adminAdmins}: Props) {
	const [groups, setGroups] = useState<Group[]>([]);
	const [isLoading, setIsLoading] = useState(false);
	const [isError, setIsError] = useState(false);

	const isMasterType = userType?.startsWith("master");

	const getData = () => {
		setIsLoading(true);

		const url = admin && !adminAdmins ? `/api/groups?admin=${admin}` : "/api/groups";
		axios
			.get<Group[]>(url)
			.then((response) => {
				if (isMasterType) return setGroups(response.data);

				const filterByAdmins = !!adminAdmins
					? [adminAdmins, ...response.data.filter((g) => g.participants.includes(adminAdmins)).flatMap((g) => g.admin)]
					: [admin];
				const adminFilter = (g: Group) => filterByAdmins.includes(g.admin) || g.participants.includes(admin || "");

				const filteredGroups = !!admin || !!adminAdmins ? response.data.filter(adminFilter) : response.data;
				return setGroups(admin ? filteredGroups.map((g) => ({...g, disableEditing: g.disableEditing || g.admin !== admin})) : filteredGroups);
			})
			.finally(() => setIsLoading(false));
	};

	useEffect(getData, [admin, adminAdmins, isMasterType]);

	return {groups, isLoading, isError, reload: getData};
}
