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

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

	return (
		/** @todo check the color tokens here */
		<div className="bn-text-xs bn-text-button bn-text-center">
			<span className="bn-font-medium bn-text-button/60 bn-whitespace-nowrap bn-mr-1">
				{label}:
			</span>
			{isAuto ? (
				<Timer initValue={diff} />
			) : (
				<span className="bn-font-semibold">{getTimeInMins(time).full}</span>
			)}
		</div>
	);
};

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

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

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

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

	return (
		<span className="bn-font-semibold bn-w-[50px]">
			{getTimeInMins(count).numbers}
		</span>
	);
};
