import { useEffect } from 'react';

interface FinalSentenceProps {
	sentence: string;
	audioFiles: string[];
}

const outputDeviceName = 'MacBook Pro Speakers (Built-in)';
let outputDeviceId: string | null = null;

export default function FinalSentence({ sentence, audioFiles }: FinalSentenceProps) {
	const listAudioDevices = async () => {
		try {
			// Request permission first
			await navigator.mediaDevices.getUserMedia({ audio: true });

			const devices = await navigator.mediaDevices.enumerateDevices();
			const audioOutput = devices.find(
				device => device.kind === 'audiooutput' && device.label === outputDeviceName,
			);
			if (audioOutput) {
				outputDeviceId = audioOutput.deviceId;
			}
		} catch (err) {
			console.error('Error listing audio devices:', err);
		}
	};

	const playAudioSequentially = async () => {
		for (const audioUrl of audioFiles) {
			const audio = new Audio(audioUrl);
			if (outputDeviceId) {
				try {
					// Дождемся загрузки аудио перед установкой устройства вывода
					await audio.load();
					// @ts-ignore - игнорируем ошибку типа, так как setSinkId может быть недоступен в некоторых браузерах
					await audio.setSinkId(outputDeviceId);
				} catch (err) {
					console.error('Error setting audio output device:', err);
				}
			}
			await new Promise(resolve => {
				audio.onended = resolve;
				audio.play().catch(err => {
					console.error('Error playing audio:', err);
					resolve(void 0);
				});
			});
		}
	};

	useEffect(() => {
		listAudioDevices();
	}, []);

	return (
		<div className="text-center">
			<p className="text-2xl mb-4">{sentence}</p>
			<button
				onClick={playAudioSequentially}
				className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded transition duration-300"
			>
				Play
			</button>
		</div>
	);
}
