import { getTimeInMins } from "@utils/getTimeInMins";
import { type ReactNode, useEffect, useState } from "react";

export const SwapTime = ({
	label,
	time, // if completed, expects time in seconds; else unix timestamp
	isCompleted = false,
}: { label: string; time: number; isCompleted: boolean }) => {
	const currentTime = Math.floor(Date.now() / 1000);
	const diff = currentTime - time;

	return (
		<div className="bn-text-accent2 bn-bg-accent2 bn-font-medium bn-text-sm bn-text-center bn-mb-1 bn-flex bn-items-center bn-space-x-1.5 bn-mx-auto bn-rounded-full bn-py-1.5 bn-px-3">
			{label}:{" "}
			{isCompleted ? (
				<TimeTag>{getTimeInMins(time).full || "0s"}</TimeTag>
			) : (
				<Timer initValue={diff} />
			)}
		</div>
	);
};

const Timer = ({ initValue }: { initValue: number }) => {
	const [count, setCount] = useState<number>(initValue);

	useEffect(() => {
		setCount(initValue);

		const timeIntervalId = setInterval(() => {
			setCount((prevTime) => prevTime + 1);
		}, 1000);

		return () => {
			clearInterval(timeIntervalId);
		};
	}, [initValue]);

	return <TimeTag>{getTimeInMins(count).fullShort}</TimeTag>;
};

const TimeTag = ({ children }: { children: ReactNode }) => {
	return (
		<div className="bn-text-accent2 bn-font-medium bn-px-0.5 bn-min-w-5 bn-whitespace-nowrap">
			{children}
		</div>
	);
};
