import { type JSX, useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";

import { ScreenTab } from "@store/globalSlice";
import type { ReduxStateType } from "@store/types";
import { filterActiveCampaigns } from "@utils/campaignExpiry";
import { twMerge } from "@utils/tailwindMerge";
import { NewCampaignLayout } from "./NewCampaignLayout";
import { campaigns } from "./campaignData";

export const CampaignBanners = () => {
	const screenTab = useSelector(
		(state: ReduxStateType) => state.global.screenTab,
	);

	const [currentBanner, setCurrentBanner] = useState(0);

	const activeCampaigns = useMemo(() => {
		return filterActiveCampaigns(campaigns);
	}, []);

	// Create banners array from active campaigns data
	const banners: JSX.Element[] = activeCampaigns.map((campaign) => (
		<NewCampaignLayout
			key={campaign.id}
			campaign={campaign}
			swapNowFn={campaign.swapNowFn}
		>
			{campaign.backgroundImage && (
				<img
					src={campaign.backgroundImage}
					alt="background"
					className={twMerge(
						"bn-absolute bn-top-0 bn-right-0",
						campaign.backgroundImageClassName,
					)}
				/>
			)}
		</NewCampaignLayout>
	));

	useEffect(() => {
		if (banners.length === 0) return;
		const interval = setInterval(() => {
			setCurrentBanner((prev) => (prev + 1) % banners.length);
		}, 10000);
		return () => clearInterval(interval);
	}, [banners.length]);

	if (screenTab !== ScreenTab.HOME) return <></>;

	return activeCampaigns.length > 0 ? (
		<div className="bn-relative bn-mt-2 bn-px-4 sm:bn-px-0">
			{banners.length > 1 && (
				<CarouselButtons
					banners={banners}
					currentBanner={currentBanner}
					setCurrentBanner={setCurrentBanner}
				/>
			)}
			<div className="bn-h-[142px]">{banners[currentBanner]}</div>
		</div>
	) : null;
};

const CarouselButtons = ({
	banners,
	currentBanner,
	setCurrentBanner,
}: {
	banners: JSX.Element[];
	currentBanner: number;
	setCurrentBanner: React.Dispatch<React.SetStateAction<number>>;
}) => {
	return (
		<div className="bn-flex bn-items-center bn-justify-center">
			{banners.map((banner, index) => (
				<button
					key={banner.key}
					type="button"
					className={`bn-size-2 rounded-full ${
						currentBanner === index ? "bn-bg-theme" : "bn-bg-[#373A3E]"
					} bn-mx-1`}
					onClick={() => setCurrentBanner(index)}
					onKeyUp={(e) => {
						if (e.key === "Enter" || e.key === " ") {
							setCurrentBanner(index);
						}
					}}
					tabIndex={0}
				/>
			))}
		</div>
	);
};
