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

import { Icon, FloatingMenu, ListTitle, ListItem } from "@ax/components";
import { IQueryValue } from "@ax/types";

import * as S from "./style";

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

	const initialState = value && value.length ? value[0].value.toString() : "all";
	const [selectedValue, setSelectedValue] = useState<string>(initialState);

	const isFilterActived = selectedValue !== "all";

	const filters: Record<string, string> = {
		all: "All",
		used: "Used",
		unused: "Unused",
	};

	useEffect(() => {
		const filterValue = value && value.length ? value[0].value.toString() : "all";
		value && setSelectedValue(filterValue);
	}, [value]);

	const setFilterQuery = (selection: any) => {
		if (!selection.length) {
			selection = "";
		}
		setSelectedValue(selection);
		filterItems("usage", [{ value: selection, label: filters[selection] }]);
	};

	const filterAllStates = () => setFilterQuery("all");
	const filterUsedState = () => setFilterQuery("used");
	const filterUnusedState = () => setFilterQuery("unused");

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

	return (
		<FloatingMenu Button={Header} position="center">
			<ListTitle>Filter by usage</ListTitle>
			<ListItem isSelected={!isFilterActived} onClick={filterAllStates}>
				All
			</ListItem>
			<ListItem isSelected={selectedValue === "used"} onClick={filterUsedState}>
				Show images in use
			</ListItem>
			<ListItem isSelected={selectedValue === "unused"} onClick={filterUnusedState}>
				Show unused images
			</ListItem>
		</FloatingMenu>
	);
};

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

export default UsageFilter;
