import { Button, Spinner, Notice } from "@wordpress/components";
import { useEffect, useRef, useState } from "@wordpress/element";
import apiFetch from "@wordpress/api-fetch";

export default function SvgMediaControl( { value, onChange } ) {
	const mediaFrameRef = useRef( null );

	const [ mediaData, setMediaData ] = useState( null );
	const [ isLoading, setIsLoading ] = useState( false );
	const [ loadError, setLoadError ] = useState( "" );

	useEffect( () => {
		let isMounted = true;

		async function loadMediaById() {
			if ( ! value ) {
				setMediaData( null );
				setLoadError( "" );
				return;
			}

			setIsLoading( true );
			setLoadError( "" );

			try {
				const mediaResponse = await apiFetch( { path: `/wp/v2/media/${ value }` } );

				if ( isMounted ) {
					setMediaData( mediaResponse || null );
				}
			} catch ( error ) {
				if ( isMounted ) {
					setMediaData( null );
					setLoadError( error?.message || "Failed to load SVG preview" );
				}
			} finally {
				if ( isMounted ) {
					setIsLoading( false );
				}
			}
		}

		loadMediaById();

		return () => {
			isMounted = false;
		};
	}, [ value ] );

	const previewUrl = mediaData?.source_url || "";
	const hasWpMedia = !! window?.wp?.media;

	const openMediaFrame = () => {
		if ( ! hasWpMedia ) {
			return;
		}

		if ( ! mediaFrameRef.current ) {
			mediaFrameRef.current = window.wp.media( {
				title: "Select SVG",
				button: { text: "Use this SVG" },
				library: { type: "image/svg+xml" },
				multiple: false,
			} );

			mediaFrameRef.current.on( "select", () => {
				const selection = mediaFrameRef.current.state().get( "selection" );
				const selectedItem = selection?.first?.();

				if ( selectedItem ) {
					const selectedId = selectedItem.get( "id" );
					onChange( selectedId ? String( selectedId ) : "" );
				}
			} );
		}

		mediaFrameRef.current.open();
	};

	return (
		<div className="jm-media-row">
			{ ! hasWpMedia ? (
				<Notice status="warning" isDismissible={ false }>
					wp.media is not available. Make sure wp_enqueue_media() is called on this admin page.
				</Notice>
			) : null }

			{ value ? (
				<>
					<div className="jm-media-preview" style={ { marginBottom: 8 } }>
						{ isLoading ? <Spinner /> : null }

						{ ! isLoading && previewUrl ? (
							<img
								src={ previewUrl }
								alt=""
								style={ {
									display: "block",
									width: 48,
									height: 48,
									objectFit: "contain",
									borderRadius: 4,
									border: "1px solid #dcdcde",
									padding: 6,
									background: "#fff",
								} }
							/>
						) : null }

						{ ! isLoading && loadError ? (
							<Notice status="warning" isDismissible={ false }>
								{ loadError }
							</Notice>
						) : null }
					</div>

					<Button variant="secondary" onClick={ openMediaFrame } disabled={ ! hasWpMedia }>
						Replace SVG
					</Button>

					<Button variant="tertiary" isDestructive onClick={ () => onChange( "" ) }>
						Clear
					</Button>
				</>
			) : (
				<Button variant="secondary" onClick={ openMediaFrame } disabled={ ! hasWpMedia }>
					Select SVG
				</Button>
			) }
		</div>
	);
}
