import React, { useState, useCallback, useRef, useEffect } from '@wordpress/element';
import classNames from 'classnames';

import { formatBytes, generateFileItem } from '../../utils/common';
import { decode } from 'js-base64';


const MediaPlayer = ({ data, accountId }) => {
	// Use the accountId from props if available, otherwise fall back to activeAccount from EDBIData
	let activeAccount;
	if (accountId) {
		const { accounts } = EDBIData;
		let accountsData;
		try {
			accountsData = typeof accounts === 'string' ? JSON.parse(decode(accounts)) : accounts;
		} catch (e) {
			console.error('Error parsing accounts data:', e);
			accountsData = [];
		}
		// Ensure accountsData is an array before using find
		if (Array.isArray(accountsData)) {
			activeAccount = accountsData.find(acc => acc.id === accountId);
		}
		// If still no activeAccount found, try to get active account
		if (!activeAccount) {
			let { activeAccount: activeAccountData } = EDBIData;
			try {
				activeAccount = typeof activeAccountData === 'string' ? JSON.parse(decode(activeAccountData)) : activeAccountData;
			} catch (e) {
				console.error('Error parsing active account data:', e);
				activeAccount = null;
			}
		}
	} else {
		let { activeAccount: activeAccountData } = EDBIData;
		try {
			activeAccount = typeof activeAccountData === 'string' ? JSON.parse(decode(activeAccountData)) : activeAccountData;
		} catch (e) {
			console.error('Error parsing active account data:', e);
			activeAccount = null;
		}
	}

	const items = data?.source?.items?.files || [];
	const settings = data?.settings?.mediaPlayer || {};
	const autoplay = settings.autoplay ?? false;


	const mediaItems = items.filter(
		item => item.mimetype && (item.mimetype.startsWith('audio/') || item.mimetype.startsWith('video/'))
	);
	
	const [currentIndex, setCurrentIndex] = useState(0);
	const playerRef = useRef(null);
	const playerInstance = useRef(null);
	
	const currentItem = mediaItems[currentIndex];
	
	useEffect(() => {
		if (playerInstance.current) {
			playerInstance.current.destroy();
			playerInstance.current = null;
		}

		if (!playerRef.current) {
			return;
		}

		playerInstance.current = new Plyr(playerRef.current, {
			controls: ['play', 'progress', 'current-time', 'mute', 'volume', 'fullscreen'],
		});

		console.log('playerInstance.current', playerInstance.current);

		// Autoplay on load if enabled
		if (autoplay) {
			playerInstance.current.once('ready', () => {
				playerInstance.current.play();
			});
		}

		// Auto play next when ended
		playerInstance.current.on('ended', () => {
			if (currentIndex + 1 < mediaItems.length) {
				setCurrentIndex(currentIndex + 1);
			}
		});
	}, [currentIndex, autoplay, mediaItems.length]);
	
	const handleSelect = index => setCurrentIndex(index);

	const genUrl = (item) => {
		// Use item's account_id if available, otherwise use the component's accountId
		const itemAccountId = item.account_id || (activeAccount ? activeAccount.id : '');
		return EDBIData.ajaxUrl + '?action=edbi_file_preview&account_id=' + itemAccountId + '&nonce=' + EDBIData?.ajaxNonce + '&id=' + item.id;
	}
	
	return (
		<div className="media-playlist" style={{ display: 'flex', gap: '2rem' }}>
		<div className="media-player" style={{ flex: 1 }}>
			<h3>{currentItem.name}</h3>
			{currentItem.mimetype.startsWith('audio') ? (
				<audio ref={playerRef} controls autoPlay={autoplay}>
					<source src={genUrl(currentItem)} type={currentItem.mimetype} />
				</audio>
			) : (
				<video
					ref={playerRef}
					controls
					playsInline
					style={{ maxWidth: '100%' }}
					autoPlay={autoplay}
				>
					<source src={genUrl(currentItem)} type={currentItem.mimetype} />
				</video>
			)}
		</div>
	
		<div className="playlist" style={{ width: '250px' }}>
			<h4>Playlist</h4>
			<ul style={{ listStyle: 'none', padding: 0 }}>
			{mediaItems.map((item, index) => (
				<li
				key={item.id}
				onClick={() => handleSelect(index)}
				style={{
					cursor: 'pointer',
					padding: '8px',
					background: index === currentIndex ? '#e2e8f0' : 'transparent',
					fontWeight: index === currentIndex ? 'bold' : 'normal',
				}}
				>
				{item.name}
				</li>
			))}
			</ul>
		</div>
		</div>
	);
	

	// return (
	// 	<div
	// 		className={classNames(
	// 			'edbi-gallery',
	// 			// `edbi-gallery--${layout}`,
	// 			// `edbi-gallery--style-${thumbnailView}`
	// 		)}
	// 		// style={{
	// 		// 	'--column-width': getColumnWidth || 'calc(100%-5px)',
	// 		// 	'--aspect-ratio': data?.settings?.gallery?.aspectRatio
	// 		// 		? data?.settings?.gallery?.aspectRatio.replace(':', ' / ')
	// 		// 		: 1,
	// 		// }}
	// 	>
	// 		Hola
	// 	</div>
	// );
};

export default MediaPlayer;
