import { __ } from "@wordpress/i18n";
import {
	useBlockProps,
	MediaPlaceholder,
	BlockControls,
	MediaReplaceFlow,
	InspectorControls,
} from "@wordpress/block-editor";
import {
	ToolbarButton,
	PanelBody,
	TextControl,
	Notice,
} from "@wordpress/components";
import { useEffect, useRef, useState } from "@wordpress/element";
import { useDispatch } from "@wordpress/data";
import { store as coreStore } from "@wordpress/core-data";
import "./editor.scss";
import { RichText } from "@wordpress/block-editor";
export default function Edit({ attributes, setAttributes }) {
	const { audioUrl, audioId, title, caption } = attributes;
	const audioRef = useRef(null);
	const plyrInstance = useRef(null);
	const { saveEntityRecord } = useDispatch(coreStore);
	const [isSavingCaption, setIsSavingCaption] = useState(false);
	const [saveMessage, setSaveMessage] = useState("");

	const saveCaptionToMedia = async (newCaption) => {
		if (!audioId) return;
		try {
			setIsSavingCaption(true);
			setSaveMessage("");
			await saveEntityRecord("postType", "attachment", {
				id: audioId,
				caption: newCaption,
			});
			setSaveMessage(
				__("Légende mise à jour dans la médiathèque.", "carhop-blocks")
			);
		} catch (e) {
			setSaveMessage(
				__(
					"Erreur lors de la mise à jour dans la médiathèque.",
					"carhop-blocks"
				)
			);
		} finally {
			setIsSavingCaption(false);
		}
	};

	const handleCaptionChange = (value) => {
		setAttributes({ caption: value });
		if (audioId) {
			void saveCaptionToMedia(value);
		}
	};

	const onSelectAudio = (media) => {
		setAttributes({
			audioUrl: media.url,
			audioId: media.id,
			// Récupérer les métadonnées depuis la médiathèque
			caption: media.caption || "",
		});
	};

	const onSelectURL = (url) => {
		setAttributes({
			audioUrl: url,
			audioId: 0,
		});
	};

	const onRemoveAudio = () => {
		setAttributes({
			audioUrl: "",
			audioId: 0,
			caption: "",
		});
	};

	// Initialize Plyr in the editor
	useEffect(() => {
		// Wait for Plyr to be loaded (via PHP)
		if (!audioUrl || !audioRef.current || typeof window.Plyr === "undefined") {
			return;
		}

		// Destroy previous instance if it exists
		if (plyrInstance.current) {
			plyrInstance.current.destroy();
		}

		// Create new Plyr instance
		plyrInstance.current = new window.Plyr(audioRef.current, {
			controls: [
				"play-large",
				"play",
				"progress",
				"current-time",
				"mute",
				"volume",
				"settings",
			],
			settings: ["speed"],
			speed: { selected: 1, options: [0.5, 0.75, 1, 1.25, 1.5, 2] },
		});

		// Cleanup on unmount
		return () => {
			if (plyrInstance.current) {
				plyrInstance.current.destroy();
				plyrInstance.current = null;
			}
		};
	}, [audioUrl]);

	return (
		<div {...useBlockProps({ className: "audio-player" })}>
			<InspectorControls>
				<PanelBody
					title={__("Informations", "carhop-blocks")}
					initialOpen={true}
				>
					<TextControl
						label={__("Titre", "carhop-blocks")}
						value={title}
						onChange={(value) => setAttributes({ title: value })}
					/>
					<TextControl
						label={__("Légende", "carhop-blocks")}
						value={caption}
						onChange={handleCaptionChange}
					/>
					{audioId ? (
						isSavingCaption ? (
							<Notice status="info" isDismissible={false}>
								{__("Sauvegarde…", "carhop-blocks")}
							</Notice>
						) : saveMessage ? (
							<Notice status="success" isDismissible={false}>
								{saveMessage}
							</Notice>
						) : null
					) : (
						<Notice status="info" isDismissible={false}>
							{__(
								"Média externe : la légende n'est pas synchronisée dans la médiathèque.",
								"carhop-blocks"
							)}
						</Notice>
					)}
				</PanelBody>
			</InspectorControls>
			<RichText
				className="audio-player__title"
				value={title}
				onChange={(value) => setAttributes({ title: value })}
				tagName="h4"
			/>
			{!audioUrl ? (
				<MediaPlaceholder
					icon="format-audio"
					onSelect={onSelectAudio}
					onSelectURL={onSelectURL}
					accept="audio/*"
					allowedTypes={["audio"]}
					labels={{
						title: __("Fichier audio", "carhop-blocks"),
						instructions: __(
							"Téléchargez un fichier audio, sélectionnez-en un depuis la médiathèque ou insérez-en un depuis une URL.",
							"carhop-blocks"
						),
					}}
				/>
			) : (
				<>
					<BlockControls>
						<MediaReplaceFlow
							mediaId={audioId}
							mediaURL={audioUrl}
							allowedTypes={["audio"]}
							accept="audio/*"
							onSelectURL={onSelectURL}
							onSelect={onSelectAudio}
						/>
						<ToolbarButton onClick={onRemoveAudio}>
							{__("Retirer", "carhop-blocks")}
						</ToolbarButton>
					</BlockControls>
					<div className="audio-player-preview">
						<audio
							ref={audioRef}
							className="js-plyr"
							src={audioUrl}
							preload="metadata"
						>
							{__(
								"Votre navigateur ne supporte pas l'élément audio.",
								"carhop-blocks"
							)}
						</audio>
					</div>
				</>
			)}
			<p className="audio-player__details">
				<span className="audio-player__details__label">Audio</span>
				<RichText
					className="audio-player__details__caption"
					placeholder={__(
						"Renseignez ici la légende de l'audio",
						"carhop-blocks"
					)}
					value={caption}
					onChange={(value) => handleCaptionChange(value)}
					tagName="span"
				/>
			</p>
		</div>
	);
}
