import React, { useEffect, useState } from "react";
import { CheckGroup, FloatingMenu, Icon, ListTitle } from "@ax/components";
import { areEquals } from "@ax/helpers";
import { IQueryValue } from "@ax/types";

import * as S from "./style";

const TypeFilter = (props: ITypeFilterProps): JSX.Element => {
	const { filterItems, filters, pointer, value } = props;

	const initialState = ["all"];
	const selectAllOption = "all";
	const arrayValues = Array.isArray(value) && value.length ? value.map((val) => val.value) : initialState;
	const [selectedValue, setSelectedValue] = useState(arrayValues);

	useEffect(() => {
		const arrayValues = Array.isArray(value) && value.length ? value.map((val) => val.value) : initialState;
		setSelectedValue(arrayValues);
	}, [value]);

	const setFilterQuery = (selection: any) => {
		if (!selection.length) {
			selection = initialState;
		}
		setSelectedValue(selection);
		const queryFilters: IQueryValue[] = selection.map((value: string | number) => {
			const label = filters.find((opt: IFilter) => opt.value === value);
			return { value, label: label?.title || "" };
		});
		filterItems(pointer, queryFilters);
	};

	const isActive = !areEquals(selectedValue, initialState);

	const Header = () => (
		<S.Types isActive={isActive}>
			Types
			<S.IconsWrapper>
				{isActive ? <Icon name="Filter" size="16" /> : <Icon name="DownArrow" size="16" />}
			</S.IconsWrapper>
		</S.Types>
	);

	return (
		<FloatingMenu Button={Header} position="left" closeOnSelect={false}>
			<ListTitle data-testid="type-filter-title">Filter by type</ListTitle>
			<S.ChecksWrapper>
				<CheckGroup
					options={filters}
					value={selectedValue}
					onChange={setFilterQuery}
					selectAllOption={selectAllOption}
					multipleSelection={true}
				/>
			</S.ChecksWrapper>
		</FloatingMenu>
	);
};

interface IFilter {
	name: string;
	value: string;
	title: string;
}

export interface ITypeFilterProps {
	filterItems(pointer: string, filter: IQueryValue[]): void;
	filters: IFilter[];
	pointer: string;
	value?: IQueryValue[];
}

export default TypeFilter;
