import {Group, User} from "@/interfaces/user";
import axios from "axios";
import {useEffect, useState} from "react";

export default function useGroups(admin?: string, userType?: string) {
	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 ? `/api/groups?admin=${admin}` : "/api/groups";
		axios
			.get<Group[]>(url)
			.then((response) => {
				if(isMasterType) {
					return setGroups(response.data);
				}
				const filter = (g: Group) => g.admin === admin || g.participants.includes(admin || "");

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

	useEffect(getData, [admin, isMasterType]);

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