import React, { useEffect, useState } from "react";

import { CheckGroupFilter } from "@ax/components";
import { isReqOk } from "@ax/helpers";
import { users } from "@ax/api";
import { IQueryValue, IUser } from "@ax/types";

const UserFilter = (props: IUserFilterProps): JSX.Element => {
	const { filterItems, value } = props;

	const filters = [
		{
			name: "all",
			value: "all",
			title: "All users (bot not included)",
		},
		{
			name: "bot",
			value: "bot",
			title: "View bot events",
		},
	];

	const [options, setOptions] = useState(filters);

	const getUsers = async () => {
		try {
			const items = await users.getUsers({ filterQuery: "?order=name-asc" });
			if (items && isReqOk(items.status)) {
				return items.data;
			}
		} catch (e) {
			console.log(e);
		}
		return false;
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: fix this
	useEffect(() => {
		getUsers()
			.then((items: IUser[]) => {
				items &&
					items.forEach((item) => {
						const newFilter = {
							name: item.id?.toString() || "",
							value: item.id?.toString() || "",
							title: item.name,
						};
						filters.push(newFilter);
					});

				setOptions(filters);
			})
			.catch((apiError) => console.log(apiError));
	}, []);

	return (
		<CheckGroupFilter
			filterItems={filterItems}
			value={value}
			pointer="users"
			label="User"
			description="Filter by User"
			initialState={["all"]}
			selectAllOption="all"
			filters={options}
			menuPosition="center"
			multipleSelection={true}
			search={true}
		/>
	);
};

export interface IUserFilterProps {
	filterItems(pointer: string, filter: IQueryValue[]): void;
	value: IQueryValue[];
}

export default UserFilter;
