import { useMemo } from "react";

import type { Token } from "@/types/index";
import { CAMPAIGN_CONFIG } from "@components/common/CampaignBanners/campaignData";
import { MIcon } from "@components/common/MIcon";
import type { ReduxStateType } from "@store/types";
import { filterActiveCampaignEntries } from "@utils/campaignExpiry";
import { useSelector } from "react-redux";

export const TokenCampaignTags = ({ token }: { token: Token }) => {
	const data = useSelector((state: ReduxStateType) => state.tokenSelector.data);

	const isSourceTokenSelector = data?.isSourceTokenSelector;
	// Check if token is eligible for any active campaign
	const eligibleCampaigns = useMemo(() => {
		const activeCampaignEntries = filterActiveCampaignEntries(
			Object.entries(CAMPAIGN_CONFIG),
		);

		return activeCampaignEntries.filter(([campaignId, config]) => {
			// Check if token matches any eligible token criteria
			return config.eligibleTokens.some(
				(eligibleToken) =>
					eligibleToken.address.toLowerCase() ===
						token.address?.toLowerCase() &&
					eligibleToken.chainId === token.chainId &&
					(eligibleToken.side === "both" ||
						(eligibleToken.side === "source" && isSourceTokenSelector) ||
						(eligibleToken.side === "destination" && !isSourceTokenSelector)),
			);
		});
	}, [token.address, token.chainId, isSourceTokenSelector]);

	if (eligibleCampaigns.length === 0) return null;

	return <Tag>Earn Rewards</Tag>;
};

const Tag = ({ children }: { children: string }) => {
	const style =
		"bn-text-accent-3 bn-bg-accent-3 bn-rounded-full bn-px-[5px] bn-py-[3px] bn-space-x-[5px] bn-text-xs bn-font-medium bn-ml-1 bn-flex bn-items-center bn-leading-[14px]";

	return (
		<div className={style}>
			<MIcon name="star_shine" classNames="bn-text-accent-3 bn-text-xs" />
			<span>{children}</span>
		</div>
	);
};
