import { __ } from '@wordpress/i18n';
import { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button, SelectControl, TextControl } from '@wordpress/components';
import { useState, useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';

// Small inline thumbnail preview of the selected poster image.
function PosterPreview( { posterId, posterUrl } ) {
  const [ url, setUrl ] = useState( '' );

  useEffect( () => {
    let cancelled = false;
    if ( posterId ) {
      apiFetch( { path: `/wp/v2/media/${ posterId }` } )
        .then( ( media ) => {
          if ( cancelled ) return;
          const sizes = media?.media_details?.sizes;
          setUrl( sizes?.thumbnail?.source_url || sizes?.medium?.source_url || media?.source_url || '' );
        } )
        .catch( () => { if ( ! cancelled ) setUrl( '' ); } );
    } else {
      setUrl( posterUrl || '' );
    }
    return () => { cancelled = true; };
  }, [ posterId, posterUrl ] );

  if ( ! url ) return null;
  return (
    <div className="axcelersblocks-image-preview" role="img" aria-label={ __( 'Selected poster', 'axcelersblocks' ) }>
      <img className="axcelersblocks-image-preview__img" src={ url } alt="" />
    </div>
  );
}

export default function VideoMediaControls( { attributes, setAttributes } ) {
  const {
    videoId, videoUrl, videoType, posterId, posterUrl,
    sourceMode, embedUrl, embedTitle, embedAspectRatio,
  } = attributes;

  const mode = sourceMode === 'embed' ? 'embed' : 'self';

  const onSelectVideo = ( media ) => {
    if ( ! media ) return;
    setAttributes( {
      videoId: media.id?.toString?.() || '',
      videoType: media.mime || media.mime_type || '',
    } );
  };

  const clearVideo = () => setAttributes( { videoId: '', videoType: '' } );

  const onSelectPoster = ( media ) => {
    if ( ! media ) return;
    setAttributes( { posterId: media.id?.toString?.() || '' } );
  };

  const clearPoster = () => setAttributes( { posterId: '' } );

  return (
    <div className="axcelersblocks-media-controls">
      <SelectControl
        label={ __( 'Source type', 'axcelersblocks' ) }
        value={ mode }
        onChange={ ( val ) => setAttributes( { sourceMode: val } ) }
        options={ [
          { label: __( 'Self-hosted (upload / URL)', 'axcelersblocks' ), value: 'self' },
          { label: __( 'Embed (YouTube, Vimeo, Dailymotion…)', 'axcelersblocks' ), value: 'embed' },
        ] }
      />

      <hr className="axcelersblocks-divider" />

      { mode === 'embed' ? (
        <>
          {/* Streaming-platform embed. */}
          <h3 className="axcelersblocks-settings-title">{ __( 'Video Platform URL', 'axcelersblocks' ) }</h3>
          <TextControl
            label={ __( 'Paste a video link', 'axcelersblocks' ) }
            value={ embedUrl || '' }
            onChange={ ( val ) => setAttributes( { embedUrl: val } ) }
            placeholder="https://www.youtube.com/watch?v=…"
            help={ __( 'YouTube, Vimeo and Dailymotion get a native player. Any other oEmbed-supported platform (TikTok, Twitch, Facebook, Wistia, SoundCloud…) is embedded automatically.', 'axcelersblocks' ) }
          />
          <SelectControl
            label={ __( 'Aspect ratio', 'axcelersblocks' ) }
            value={ embedAspectRatio || '16 / 9' }
            onChange={ ( val ) => setAttributes( { embedAspectRatio: val } ) }
            options={ [
              { label: '16 : 9 (widescreen)', value: '16 / 9' },
              { label: '4 : 3', value: '4 / 3' },
              { label: '1 : 1 (square)', value: '1 / 1' },
              { label: '21 : 9 (cinematic)', value: '21 / 9' },
              { label: '9 : 16 (vertical)', value: '9 / 16' },
            ] }
          />
          <TextControl
            label={ __( 'Title (accessibility)', 'axcelersblocks' ) }
            value={ embedTitle || '' }
            onChange={ ( val ) => setAttributes( { embedTitle: val } ) }
            placeholder={ __( 'Describe the video for screen readers', 'axcelersblocks' ) }
          />
          <p className="axcelersblocks-settings-help">
            { __( 'Playback options (autoplay, mute, loop, controls) below apply to YouTube, Vimeo and Dailymotion where the platform allows it.', 'axcelersblocks' ) }
          </p>
        </>
      ) : (
        <SelfHostedControls
          attributes={ attributes }
          setAttributes={ setAttributes }
          videoId={ videoId }
          videoUrl={ videoUrl }
          videoType={ videoType }
          posterId={ posterId }
          posterUrl={ posterUrl }
          onSelectVideo={ onSelectVideo }
          clearVideo={ clearVideo }
          onSelectPoster={ onSelectPoster }
          clearPoster={ clearPoster }
        />
      ) }
    </div>
  );
}

function SelfHostedControls( {
  setAttributes, videoId, videoUrl, videoType, posterId, posterUrl,
  onSelectVideo, clearVideo, onSelectPoster, clearPoster,
} ) {
  return (
    <>
      {/* Self-hosted video from the Media Library (includes upload). */}
      <h3 className="axcelersblocks-settings-title">{ __( 'Use from Media Library', 'axcelersblocks' ) }</h3>

      <MediaUploadCheck>
        <MediaUpload
          onSelect={ onSelectVideo }
          allowedTypes={ [ 'video' ] }
          value={ videoId ? parseInt( videoId, 10 ) : undefined }
          render={ ( { open } ) => (
            <Button variant="secondary" onClick={ open }>
              { videoId ? __( 'Replace Video', 'axcelersblocks' ) : __( 'Select Video', 'axcelersblocks' ) }
            </Button>
          ) }
        />
      </MediaUploadCheck>
      { videoId && (
        <Button variant="link" isDestructive onClick={ clearVideo } style={ { marginLeft: '10px' } }>
          { __( 'Clear', 'axcelersblocks' ) }
        </Button>
      ) }

      <hr className="axcelersblocks-divider" />

      {/* External / self-hosted URL fallback. */}
      <h3 className="axcelersblocks-settings-title">{ __( 'External Video URL', 'axcelersblocks' ) }</h3>
      <TextControl
        label={ __( 'Video URL (external only)', 'axcelersblocks' ) }
        value={ videoUrl }
        onChange={ ( val ) => setAttributes( { videoUrl: val } ) }
        placeholder="https://example.com/video.mp4"
        help={ __( 'Used only when Dynamic is off and no Media Library video is selected.', 'axcelersblocks' ) }
      />
      <TextControl
        label={ __( 'MIME type (optional)', 'axcelersblocks' ) }
        value={ videoType }
        onChange={ ( val ) => setAttributes( { videoType: val } ) }
        placeholder="video/mp4"
        help={ __( 'e.g. video/mp4, video/webm, video/ogg. Helps the browser pick the source.', 'axcelersblocks' ) }
      />

      <hr className="axcelersblocks-divider" />

      {/* Poster (the still frame shown before playback). */}
      <h3 className="axcelersblocks-settings-title">{ __( 'Poster Image', 'axcelersblocks' ) }</h3>
      <p className="axcelersblocks-settings-help">
        { __( 'Shown before the video plays. Set as the video element’s poster attribute.', 'axcelersblocks' ) }
      </p>

      <PosterPreview posterId={ posterId } posterUrl={ posterUrl } />

      <MediaUploadCheck>
        <MediaUpload
          onSelect={ onSelectPoster }
          allowedTypes={ [ 'image' ] }
          value={ posterId ? parseInt( posterId, 10 ) : undefined }
          render={ ( { open } ) => (
            <Button variant="secondary" onClick={ open }>
              { posterId ? __( 'Replace Poster', 'axcelersblocks' ) : __( 'Select Poster', 'axcelersblocks' ) }
            </Button>
          ) }
        />
      </MediaUploadCheck>
      { posterId && (
        <Button variant="link" isDestructive onClick={ clearPoster } style={ { marginLeft: '10px' } }>
          { __( 'Clear', 'axcelersblocks' ) }
        </Button>
      ) }

      <TextControl
        label={ __( 'External Poster URL', 'axcelersblocks' ) }
        value={ posterUrl }
        onChange={ ( val ) => setAttributes( { posterUrl: val } ) }
        placeholder="https://example.com/poster.jpg"
        help={ __( 'Used only when no Media Library poster is selected.', 'axcelersblocks' ) }
      />
    </>
  );
}
