/**
 * External dependencies
 */
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

/**
 * WordPress dependencies
 */
import { TextControl, Panel, PanelBody } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const VideoThumbnails = ( { handleSettingChange } ) => {
	const videoThumbnails = useSelector( ( state ) => state.mediaSettings.video.video_thumbnails ) || 5;
	const [ videoThumbnailsInput, setVideoThumbnailsInput ] = useState( String( videoThumbnails ) );

	useEffect( () => {
		setVideoThumbnailsInput( String( videoThumbnails ) );
	}, [ videoThumbnails ] );

	const handleVideoThumbnailsInputChange = ( value ) => {
		if ( /^\d{0,2}$/.test( value ) ) {
			setVideoThumbnailsInput( value );
		}
	};

	const validateVideoThumbnails = () => {
		const value = parseInt( videoThumbnailsInput, 10 );
		let validatedValue;

		if ( Number.isNaN( value ) || value < 1 ) {
			validatedValue = 1;
		} else if ( value > 10 ) {
			validatedValue = 10;
		} else {
			validatedValue = value;
		}

		setVideoThumbnailsInput( String( validatedValue ) );
		if ( validatedValue !== videoThumbnails ) {
			handleSettingChange( 'video_thumbnails', validatedValue );
		}
	};

	return (
		<Panel
			heading={ __( 'Video Thumbnails', 'godam' ) }
			className="godam-panel"
		>
			<PanelBody>
				<div className="godam-form-group">
					<label className="label-text" htmlFor="video_thumbnails_count">
						{ __( 'Number of video thumbnails generated', 'godam' ) }
					</label>
					<TextControl
						className="godam-input"
						type="number"
						min="1"
						max="10"
						value={ videoThumbnailsInput }
						onChange={ ( value ) => handleVideoThumbnailsInputChange( value ) }
						onBlur={ validateVideoThumbnails }
						help={ __( `This field specifies the number of video thumbnails that will be generated by the GoDAM. To choose from the generated thumbnails for a video, go to Media > Edit > Video Thumbnails. Thumbnails are only generated when the video is first uploaded. Please enter a value between 1 and 10`, 'godam' ) }
					/>
				</div>
			</PanelBody>

		</Panel>
	);
};

export default VideoThumbnails;
