import React, { useEffect, useState } from 'react';
import { API, plugin_root_url } from '@Utils/helper';

import Preloader from '@Components/Loader/Preloader';
import './download-attachment.scss';

const DownloadAttachment = ( { id } ) => {
	const [ attachment, setAttachment ] = useState( false );
	const [ loading, setLoading ] = useState( false );

	useEffect( () => {
		if ( id ) {
			setLoading( true );
			API.get( `wp/v2/media/${ id }` ).then( ( res ) => {
				setAttachment( {
					title: res?.data?.title.rendered,
					url: res?.data?.source_url,
				} );
				setLoading( false );
			} );
		}
	}, [ id ] );

	return (
		<a
			href={ attachment?.url }
			className="quizpress-download-attachment"
			target="_blank"
			download
			rel="noreferrer"
		>
			{ loading ? (
				<div className="quizpress-preloader">
					<Preloader />
				</div>
			) : (
				<>
					<p className="quizpress-download-attachment__name">
						{ attachment?.title }
					</p>
					<img
						src={ `${ plugin_root_url }assets/images/downloadAttachment.png` }
						alt=""
					/>
				</>
			) }
		</a>
	);
};

export default DownloadAttachment;
