import { Link, LinkProps, useNavigate } from "react-router-dom";
import useRole from "../../hooks/useRole";
import {encodeParams} from "../../helpers/encodedParams";
import { getUserIdByAfm } from "../../API/rescom";

interface LinkWithQueryProps extends LinkProps {
    state?: any;
    inheritRole?: string;
    customClass?: string;
    anchor?: string;
    extraParams?: Record<string, string>;  // ✅ changed from string to Record
}

export const LinkWithRole = ({
                                 children,
                                 inheritRole,
                                 to,
                                 customClass,
                                 extraParams = {},
                                 anchor,
                                 ...props
                             }: LinkWithQueryProps) => {
    const navigate = useNavigate();
    const roleFromHook = useRole();
    const role = inheritRole || roleFromHook;

    const handleClick = async (e: React.MouseEvent) => {
        if (!anchor) return;
        e.preventDefault();
        try {
            const res = await getUserIdByAfm(anchor);
            const userId = res.data;
            const basePath = typeof to === "string" ? to : to.pathname || "";
            const finalPath = basePath.includes(":id")
                ? basePath.replace(":id", userId)
                : `${basePath}/${userId}`;

            navigate(`${finalPath}?t=${encodeParams({ activeRole: role ?? '', ...extraParams })}`);
        } catch (err) {
            console.error("Failed to fetch user_id from anchor", err);
        }
    };

    if (anchor) {
        return (
            <a href="#" onClick={handleClick} {...props}>
                {children}
            </a>
        );
    }

    return (
        <Link className={customClass} to={`${to}?t=${encodeParams({ activeRole: role ?? '', ...extraParams })}`} {...props}>
            {children}
        </Link>
    );
};
