import classNames from "classnames";
import Link from "next/link";
import { useRouter } from "next/router";
import React, { useEffect } from "react";

import Typography, { ITypo } from "../../Typography";
import classes from "./classes.module.scss";
import useHoverable from "@Front/Hooks/useHoverable";

export type IHeaderLinkProps = {
	text: string | JSX.Element;
	path: string;
	routesActive?: string[];
};

export default function HeaderLink(props: IHeaderLinkProps) {
	const router = useRouter();
	const { pathname } = router;
	const [isActive, setIsActive] = React.useState(props.path === pathname);
	const { handleMouseLeave, handleMouseEnter, isHovered } = useHoverable();

	useEffect(() => {
		setIsActive(false);
		if (props.path === pathname) setIsActive(true);
		if (props.routesActive) {
			for (const routeActive of props.routesActive) {
				if (isActive) break;
				if (pathname.includes(routeActive)) setIsActive(true);
			}
		}
	}, [isActive, pathname, props.path, props.routesActive]);

	if (props.path !== "" && props.path !== undefined) {
		return (
			<Link
				href={props.path}
				className={classNames(classes["root"], isActive && classes["active"])}
				onMouseEnter={handleMouseEnter}
				onMouseLeave={handleMouseLeave}>
				<div className={classes["content"]}>
					<Typography typo={isActive || isHovered ? ITypo.P_SB_18 : ITypo.NAV_HEADER_18}>{props.text}</Typography>
				</div>
				<div className={classes["underline"]} data-active={(isActive || isHovered).toString()} />
			</Link>
		);
	} else {
		return (
			<div className={classNames(classes["root"], classes["desactivated"])}>
				<div className={classes["content"]}>
					<Typography typo={ITypo.NAV_HEADER_18}>{props.text}</Typography>
				</div>
			</div>
		);
	}
}
