/**
 * ImageSelector Component
 * 
 * WordPress Media Library integration for bulk image assignment
 */

import React from 'react';
import { useState } from 'react';
import React from 'react';
import { useTranslation } from 'react-i18next';

interface Props {
  onSelect: (imageId: number, imageUrl: string) => void;
  selectedImageUrl?: string;
}

export default function ImageSelector({ onSelect, selectedImageUrl }: Props) {
  const { t } = useTranslation();
  const [isSelecting, setIsSelecting] = useState(false);

  const openMediaLibrary = () => {
    // @ts-ignore - WordPress wp.media is available globally
    if (typeof wp !== 'undefined' && wp.media) {
      const frame = wp.media({
        title: t('bulk.select_image'),
        button: {
          text: t('bulk.select_image'),
        },
        multiple: false,
      });

      frame.on('select', () => {
        const attachment = frame.state().get('selection').first().toJSON();
        onSelect(attachment.id, attachment.url);
        setIsSelecting(false);
      });

      frame.open();
      setIsSelecting(true);
    } else {
      console.error('WordPress Media Library not available');
    }
  };

  return (
    <div className="space-y-4">
      <button
        type="button"
        onClick={openMediaLibrary}
        disabled={isSelecting}
        className="w-full px-4 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2"
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
        {t('bulk.select_image')}
      </button>

      {selectedImageUrl && (
        <div className="relative border-2 border-gray-300 rounded-lg p-4">
          <img
            src={selectedImageUrl}
            alt="Selected"
            className="w-full h-48 object-contain rounded"
          />
          <div className="mt-2 text-sm text-gray-600 text-center">
            {t('bulk.image_selected')}
          </div>
        </div>
      )}

      {!selectedImageUrl && (
        <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center text-gray-500">
          <svg className="w-12 h-12 mx-auto mb-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
          <p className="text-sm">{t('bulk.no_image_selected')}</p>
        </div>
      )}
    </div>
  );
}
