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

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

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

	const filters = [
		{
			name: "all",
			value: "all",
			title: "ALL",
		},
	];

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

	const getEvents = async () => {
		try {
			const items = await logs.getLogActivityEventTypes();
			if (items && isReqOk(items.status)) {
				return items.data;
			}
		} catch (e) {
			console.log(e);
		}
		return false;
	};

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

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

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

interface IEventType {
	id: number;
	title: string;
	description: string;
}

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

export default EventFilter;
