import { type MutableRefObject, useEffect, useRef, useState } from "react";

import { twMerge } from "@utils/tailwindMerge";
import { MIcon } from "./MIcon";
import { Tooltip } from "./Tooltip";

export const Sound = ({
	source,
	play,
	classNames,
}: { source: string; play: boolean; classNames?: string }) => {
	const audioRef = useRef() as MutableRefObject<HTMLAudioElement>;

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (typeof window !== "undefined") {
			audioRef.current = new Audio(source);
		}
	}, []);

	useEffect(() => {
		if (play && soundEnabled) {
			audioRef.current.muted = false;
			audioRef.current.play();
		}
	}, [play, audioRef]);

	const [soundEnabled, enableSound] = useState<boolean>(false);

	function toggleSound() {
		if (soundEnabled) {
			audioRef.current.muted = true;
			audioRef.current.play();
		}

		enableSound(!soundEnabled);
	}

	const btnStyle = twMerge(
		"bn-text-primary bn-bg-transparent bn-size-8 bn-rounded-full bn-bg-layer-2 bn-flex bn-items-center bn-justify-center bn-border-none bn-cursor-pointer",
		classNames,
	);
	// biome-ignore format:
	const iconStyle = `${soundEnabled ? 'bn-text-primary' : 'bn-text-secondary'} hover:bn-text-primary bn-text-base`;

	return (
		<Tooltip content="Enable Sound Notification">
			<button type="button" className={btnStyle} onClick={toggleSound}>
				<MIcon
					name={soundEnabled ? "volume_up" : "volume_off"}
					classNames={iconStyle}
				/>
			</button>
		</Tooltip>
	);
};
