import classNames from "classnames";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import classes from "./classes.module.scss";
import { IAppRule } from "@Front/Api/Entities/rule";
import Rules, { RulesMode } from "@Front/Components/Elements/Rules";
import { IHeaderLinkProps } from "../../../HeaderLink";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import HeaderSubmenuLink from "../../../HeaderSubmenu/HeaderSubmenuLink";
import useToggle from "@Front/Hooks/useToggle";
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";

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(true);
	const { active: isSubmenuOpened, toggle } = useToggle();

	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"]}>
				<div className={classNames(classes["root"], (isActive || isSubmenuOpened) && classes["active"])}>
					<div className={classes["content"]} onClick={toggle}>
						<Typography typo={isActive || isSubmenuOpened ? ITypo.P_SB_18 : ITypo.NAV_HEADER_18}>{props.text}</Typography>
						{isSubmenuOpened ? <ChevronUpIcon height="20" width="20" /> : <ChevronDownIcon height="20" width="20" />}
					</div>
					<div className={classes["underline"]} data-active={(isActive || isSubmenuOpened).toString()} />
					{isSubmenuOpened && (
						<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>
	);
}
