import {Module} from "@/interfaces";
import {formatTimeInMinutes} from "@/utils/string";
import clsx from "clsx";
import {useEffect, useRef, useState} from "react";
import {BsPauseFill, BsPlayFill} from "react-icons/bs";
import ProgressBar from "./ProgressBar";

interface Props {
	src: string;
	color: "red" | "rose" | "purple" | Module;
	autoPlay?: boolean;
	disabled?: boolean;
	onEnd?: () => void;
	disablePause?: boolean;
}

export default function AudioPlayer({src, color, autoPlay = false, disabled = false, onEnd, disablePause = false}: Props) {
	const [isPlaying, setIsPlaying] = useState(false);
	const [duration, setDuration] = useState(0);
	const [currentTime, setCurrentTime] = useState(0);

	const audioPlayerRef = useRef<HTMLAudioElement | null>(null);

	useEffect(() => {
		const durationInterval = setInterval(() => {
			if (duration > 0) clearInterval(durationInterval);

			const seconds = Math.floor(audioPlayerRef?.current?.duration || 0);
			if (seconds > 0) setDuration(seconds);
		}, 300);

		if (duration > 0) clearInterval(durationInterval);

		return () => {
			clearInterval(durationInterval);
		};
	}, [duration]);

	useEffect(() => {
		let playingInterval: NodeJS.Timer | undefined = undefined;
		if (isPlaying) {
			playingInterval = setInterval(() => setCurrentTime((prev) => prev + 1), 1000);
		} else if (playingInterval) {
			clearInterval(playingInterval);
		}

		return () => {
			if (playingInterval) clearInterval(playingInterval);
		};
	}, [isPlaying]);

	const togglePlayPause = () => {
		const prevValue = isPlaying;
		setIsPlaying(!prevValue);
		if (!prevValue) {
			audioPlayerRef?.current?.play();
		} else {
			audioPlayerRef?.current?.pause();
		}
	};

	return (
		<div className="w-full h-fit flex gap-4 items-center mt-2">
			{isPlaying && (
				<BsPauseFill
					className={clsx("text-mti-gray-cool cursor-pointer w-5 h-5", (disabled || disablePause) && "opacity-60 cursor-not-allowed")}
					onClick={disabled || disablePause ? undefined : togglePlayPause}
				/>
			)}
			{!isPlaying && (
				<BsPlayFill
					className={clsx("text-mti-gray-cool cursor-pointer w-5 h-5", disabled && "opacity-60 cursor-not-allowed")}
					onClick={disabled ? undefined : togglePlayPause}
				/>
			)}
			<audio
				src={src}
				autoPlay={autoPlay}
				ref={audioPlayerRef}
				preload="metadata"
				onEnded={() => {
					setIsPlaying(false);
					setCurrentTime(0);
					if (onEnd) onEnd();
				}}
			/>
			<div className="flex flex-col gap-2 w-full relative">
				<div className="absolute w-full flex justify-between -top-5 text-xs px-1">
					<span>{formatTimeInMinutes(currentTime)}</span>
					<span>{formatTimeInMinutes(duration)}</span>
				</div>
				<ProgressBar label="" color={color} useColor percentage={(currentTime * 100) / duration} className="h-3 w-full" />
			</div>
		</div>
	);
}
