/**
 * Media Upload Component
 * 
 * WordPress media library integration for uploading images
 * 
 * @package ProRank\SEO
 * @since 1.0.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { MediaUpload as WPMediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';
import ProrankButton from './ProrankButton';

interface MediaUploadProps {
  value?: number | string;
  onChange: (value: number | string) => void;
  allowedTypes?: string[];
  render?: (props: { open: () => void }) => React.ReactNode;
  label?: string;
  help?: string;
  multiple?: boolean;
}

const MediaUpload: React.FC<MediaUploadProps> = ({
  value,
  onChange,
  allowedTypes = ['image'],
  render,
  label = __('Select Image', 'prorank-seo'),
  help,
  multiple = false
}) => {
  const [mediaUrl, setMediaUrl] = useState<string>('');
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (value && typeof value === 'number') {
      // Fetch media details if we have an ID
      setIsLoading(true);
      wp.media.attachment(value).fetch().then(() => {
        const attachment = wp.media.attachment(value);
        setMediaUrl(attachment.get('url'));
        setIsLoading(false);
      }).catch(() => {
        setIsLoading(false);
      });
    } else if (typeof value === 'string') {
      setMediaUrl(value);
    }
  }, [value]);

  const onSelectMedia = (media: any) => {
    if (multiple && Array.isArray(media)) {
      // Handle multiple selection
      const ids = media.map(m => m.id);
      onChange(ids.join(','));
    } else {
      // Single selection
      const singleMedia = Array.isArray(media) ? media[0] : media;
      onChange(singleMedia.id);
      setMediaUrl(singleMedia.url);
    }
  };

  const onRemoveMedia = () => {
    onChange('');
    setMediaUrl('');
  };

  // Use WordPress MediaUpload if available
  if (typeof wp !== 'undefined' && wp.media) {
    return (
      <MediaUploadCheck>
        <div className="prorank-media-upload">
          {help && <p className="description">{help}</p>}
          
          <WPMediaUpload
            onSelect={onSelectMedia}
            allowedTypes={allowedTypes}
            value={value}
            multiple={multiple}
            render={({ open }) => (
              <>
                {render ? (
                  render({ open })
                ) : (
                  <div className="prorank-media-upload-controls">
                    {mediaUrl && !isLoading && (
                      <div className="prorank-media-preview">
                        <img 
                          src={mediaUrl} 
                          alt={__('Selected media', 'prorank-seo')}
                          style={{ 
                            maxWidth: '200px', 
                            maxHeight: '200px',
                            marginBottom: '10px',
                            border: '1px solid #ddd',
                            borderRadius: '4px',
                            padding: '4px'
                          }}
                        />
                      </div>
                    )}
                    
                    <div className="prorank-media-buttons" style={{ display: 'flex', gap: '8px' }}>
                      <ProrankButton
                        variant="secondary"
                        onClick={open}
                        size="small"
                      >
                        {mediaUrl ? __('Change Image', 'prorank-seo') : label}
                      </ProrankButton>
                      
                      {mediaUrl && (
                        <ProrankButton
                          variant="tertiary"
                          onClick={onRemoveMedia}
                          size="small"
                          isDestructive
                        >
                          {__('Remove', 'prorank-seo')}
                        </ProrankButton>
                      )}
                    </div>
                  </div>
                )}
              </>
            )}
          />
        </div>
      </MediaUploadCheck>
    );
  }

  // Fallback for when WordPress MediaUpload is not available
  return (
    <div className="prorank-media-upload-fallback">
      {help && <p className="description">{help}</p>}
      
      <input
        type="url"
        value={mediaUrl}
        onChange={(e) => {
          setMediaUrl(e.target.value);
          onChange(e.target.value);
        }}
        placeholder={__('Enter image URL', 'prorank-seo')}
        className="regular-text"
        style={{ marginBottom: '10px' }}
      />
      
      {mediaUrl && (
        <div className="prorank-media-preview">
          <img 
            src={mediaUrl} 
            alt={__('Selected media', 'prorank-seo')}
            style={{ 
              maxWidth: '200px', 
              maxHeight: '200px',
              marginTop: '10px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              padding: '4px'
            }}
            onError={(e) => {
              e.currentTarget.style.display = 'none';
            }}
          />
        </div>
      )}
    </div>
  );
};

export default MediaUpload;