import React, { useState } from "react";
import MenuList from "../MenuList";
import { IFolderTree } from "@ax/types";
import { Icon } from "@ax/components";
import { trimText } from "@ax/helpers";

import * as S from "./style";

const MenuItem = (props: IMenuItem) => {
	const { item, trimNames, folderID, hidden, createAction, onClick } = props;
	const { id, name } = item;

	const [isExpanded, setIsExpanded] = useState(true);

	const hasChildren =
		item.children &&
		item.children.filter((listItem) => !hidden || (hidden && !hidden.includes(listItem.id))).length > 0;

	const handleToggle = (e: React.MouseEvent<HTMLDivElement>) => {
		e.stopPropagation();
		setIsExpanded((prev) => !prev);
	};

	const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
		e.stopPropagation();
		onClick(id);
	};

	const getIcon = (item: IFolderTree) => {
		if (item.children && item.children.length > 0) {
			return isExpanded ? <Icon name="DownArrow" size="16" /> : <Icon name="RightArrow" size="16" />;
		} else {
			return <></>;
		}
	};

	const NewFolderButton = () =>
		createAction ? (
			<S.NewIconWrapper onClick={createAction}>
				<Icon name="newFolder" size="16" />
			</S.NewIconWrapper>
		) : (
			<></>
		);

	if (hidden?.includes(id)) {
		return <></>;
	}

	return (
		<li>
			<S.ItemWrapper>
				<S.Item onClick={handleClick} selected={folderID === item.id}>
					{hasChildren && <S.ArrowWrapper onClick={handleToggle}>{getIcon(item)}</S.ArrowWrapper>}
					<S.IconWrapper>
						<Icon name="project" size="16" />
					</S.IconWrapper>
					<S.Name>{trimNames ? trimText(name, 15) : name}</S.Name>
					<NewFolderButton />
				</S.Item>
			</S.ItemWrapper>
			{hasChildren && isExpanded && (
				<S.ListWrapper>
					<MenuList
						list={item.children}
						hidden={hidden}
						trimNames={trimNames}
						createAction={createAction}
						folderID={folderID}
						onClick={onClick}
					/>
				</S.ListWrapper>
			)}
		</li>
	);
};

interface IMenuItem {
	item: IFolderTree;
	folderID: number;
	trimNames?: boolean;
	hidden?: number[];
	onClick(folderID: number): void;
	createAction?(): void;
}

export default MenuItem;
