"use client";
import { revalidate } from "@/server/actions/timer";
import { fetcher } from "@/utils/fetch";
import useSWR from "swr";

interface CountdownProps {
	jobId: string;
}
export function Countdown(props: CountdownProps) {
	const { jobId } = props;
	const { data, error, isLoading } = useSWR(`/api/job/${jobId}/remaining-time`, fetcher, {
		refreshInterval: 1000 * 30,
	});

	if (error) {
		return <span className="text-red-500">Ein Fehler ist aufgetreten.</span>;
	}

	if (isLoading) {
		return <>...</>;
	}

	console.log(data);

	const days = Math.floor(data.remainingTime / (1000 * 60 * 60 * 24));
	const hours = Math.floor((data.remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((data.remainingTime % (1000 * 60 * 60)) / (1000 * 60));
	const seconds = Math.floor((data.remainingTime % (1000 * 60)) / 1000);

	if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) {
		revalidate();
	}

	return (
		<span className="tabular-nums" suppressHydrationWarning>
			{days > 0 && <>{`${days}`.padStart(2, "0")}d </>}
			{hours === 0 && minutes === 0 ? (
				<>{`${seconds}`.padStart(2, "0")}s</>
			) : (
				<>
					{`${hours}`.padStart(2, "0")}h {`${minutes}`.padStart(2, "0")}min
				</>
			)}
		</span>
	);
}
