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

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

import * as S from "./style";

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

	const [selectedValue, setSelectedValue] = useState<string>("");

	const isFilterActived = selectedValue !== "";

	useEffect(() => {
		value && setSelectedValue(value);
	}, [value]);

	const setFilterQuery = (selection: any) => {
		if (!selection.length) {
			selection = "";
		}
		setSelectedValue(selection);
		filterItems("filterUsage", selection);
	};

	const filterAllStates = () => setFilterQuery("");
	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 files in use
			</ListItem>
			<ListItem isSelected={selectedValue === "unused"} onClick={filterUnusedState}>
				Show unused files
			</ListItem>
		</FloatingMenu>
	);
};

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

export default UsageFilter;
