"use client";

import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { Progress } from "~/components/ui/progress";

export const ProgressRedirect = ({ href }: { href: string }) => {
	const [progress, setProgress] = useState(0);
	const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null);
	const router = useRouter();
	const handleProgress = () => {
		setProgress((prev) => {
			if (prev >= 100) {
				if (intervalId) {
					clearInterval(intervalId);
				}

				return 100;
			}
			return prev + 20; // Increment progress by 20% every second
		});
	};
	useEffect(() => {
		const id = setInterval(handleProgress, 1000); // Update progress every second
		setIntervalId(id);
		return () => {
			if (id) {
				clearInterval(id);
			}
		};
	}, []);

	useEffect(() => {
		async function redirect() {
			await router.push(href);
		}

		if (progress === 100) {
			redirect().catch((error) => {
				console.error("Error during redirect:", error);
			});
		}
	}, [progress]);
	return (
		<div className="flex flex-col items-center justify-center gap-4">
			<Progress className="h-3" value={progress} />

			<div className="flex items-center justify-center gap-2">
				<p className="text-muted-foreground">
					Stai venendo reindirizzato... oppure
				</p>
				<Link
					className="font-semibold underline underline-offset-1"
					href={href}
				>
					Clicca qui
				</Link>
			</div>
		</div>
	);
};
