import * as React from "react";
import * as CSS from 'csstype';
import { IProductCategoryItem } from "../../../../apiModels/ViewModels";

type ProductCategoryDropdownItemProps = {
	activeFilterExpression: string,
	categories: IProductCategoryItem[],
	category: IProductCategoryItem,
	level: number,
	onFilterExpressionChange(categoryId: number): void,
	parentId: number
};

export default function ProductCategoryDropdownItem({ activeFilterExpression, categories, category, level, onFilterExpressionChange, parentId }: ProductCategoryDropdownItemProps) {
	const initDropdownStyle: CSS.Properties = {
		position: 'absolute',
		left: `${level === 0 ? 0 : 180}px`,
		top: '50px',
		background: '#222222',
		width: '180px',
		zIndex: 9,
		padding: '5px 0',
		WebkitTransition: 'all, 0.3s',
		MozTransition: 'all, 0.3s',
		msTransition: 'all, 0.3s',
		OTransition: 'all, 0.3s',
		transition: 'all, 0.3s',
		opacity: '0',
		visibility: 'hidden'
	};
	
	const visibleDropdownStyle: CSS.Properties = {
		position: 'absolute',
		left: `${level === 0 ? 0 : 180}px`,
		marginTop: `${level === 0 ? 0 : -30}px`,
		top: '25px',
		background: '#222222',
		width: '180px',
		zIndex: 9,
		padding: '5px 0',
		WebkitTransition: 'all, 0.3s',
		MozTransition: 'all, 0.3s',
		msTransition: 'all, 0.3s',
		OTransition: 'all, 0.3s',
		transition: 'all, 0.3s',
		opacity: '1',
		visibility: 'visible'
	};

	// hook ktery umoznuje pridat state do function component
	const [dropdownStyle, setDropdownStyle] = React.useState(initDropdownStyle);

	// get descendants
	const descendants = categories
		.filter(i => i.parentID === category.id)
		.sort((a, b) => (a.name > b.name ? 1 : -1));

	return (
		<React.Fragment>
			<li className={
				`${level === 0 ? '' : 'dropdown__item__li'} ${activeFilterExpression === category.id.toString() ? 'active' : ''}`
				}
				onMouseOver={() => setDropdownStyle(visibleDropdownStyle)}
				onMouseLeave={() => setDropdownStyle(initDropdownStyle)}
			>

				<a className={level === 0 ? '' : 'dropdown__item__a'}
					onClick={() => onFilterExpressionChange(category.id)}>
					{category.name}
				</a>

				{descendants.length
					? <ul key={`categoryDropdownMenu-${category.id}`} style={dropdownStyle}>
						{descendants.map((descendant: IProductCategoryItem) => (
							<ProductCategoryDropdownItem
								key={`categoryDropdownItem-${descendant.id}`}
								activeFilterExpression={activeFilterExpression}
								categories={categories}
								category={descendant}
								level={level + 1}
								onFilterExpressionChange={onFilterExpressionChange}
								parentId={category.id} />
						))}
					</ul>
					: null}
			</li>
		</React.Fragment>
	);
}
