import classNames from "classnames";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { IHeaderLinkProps } from "../HeaderLink";

import Typography, { ITypo, ITypoColor } from "../../Typography";
import classes from "./classes.module.scss";
import useHoverable from "@Front/Hooks/useHoverable";
import HeaderSubmenuLink from "./HeaderSubmenuLink";
import { IAppRule } from "@Front/Api/Entities/rule";
import Rules, { RulesMode } from "@Front/Components/Elements/Rules";

type IProps = {
	text: string | JSX.Element;
	links: (IHeaderLinkProps & {
		rules?: IAppRule[];
	})[];
};

export default function HeaderSubmenu(props: IProps) {
	const router = useRouter();
	const { pathname } = router;
	const [isActive, setIsActive] = useState(false);
	const { handleMouseLeave, handleMouseEnter, isHovered } = useHoverable(100);

	useEffect(() => {
		setIsActive(false);
		if (props.links.some((link) => link.path === pathname)) setIsActive(true);
		if (props.links.some((link) => link.routesActive?.some((routeActive) => pathname.includes(routeActive)))) setIsActive(true);
	}, [isActive, pathname, props.links]);

	return (
		<Rules mode={RulesMode.OPTIONAL} rules={props.links.flatMap((link) => link.rules ?? [])}>
			<div className={classes["container"]} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
				<div className={classNames(classes["root"], (isActive || isHovered) && classes["active"])}>
					<div className={classes["content"]}>
						<Typography
							typo={isActive || isHovered ? ITypo.TEXT_LG_SEMIBOLD : ITypo.TEXT_LG_REGULAR}
							color={isActive || isHovered ? ITypoColor.COLOR_NEUTRAL_950 : ITypoColor.COLOR_NEUTRAL_500}>
							{props.text}
						</Typography>
					</div>
					<div className={classes["underline"]} data-active={(isActive || isHovered).toString()} />
					{isHovered && (
						<div className={classes["sub-menu"]}>
							{props.links.map((link) => (
								<Rules mode={RulesMode.NECESSARY} rules={link.rules ?? []} key={link.path}>
									<HeaderSubmenuLink {...link} />
								</Rules>
							))}
						</div>
					)}
				</div>
			</div>
		</Rules>
	);
}
