import React, { useState } from 'react';
import api from '../utils/api';

const ImageUploader = ({ images = [], onChange, showError, showSuccess, type = 'gallery' }) => {
    const [uploading, setUploading] = useState(false);

    const openMediaLibrary = () => {
        // Open WordPress Media Library
        if (window.wp && window.wp.media) {
            const frame = window.wp.media({
                title: type === 'featured' ? 'Select Featured Image' : 'Select Gallery Images',
                button: {
                    text: 'Use this image'
                },
                multiple: type !== 'featured'
            });

            frame.on('select', function() {
                const selection = frame.state().get('selection');
                const selectedImages = selection.map(attachment => {
                    attachment = attachment.toJSON();
                    return {
                        id: attachment.id,
                        src: attachment.url,
                        alt: attachment.alt || '',
                        name: attachment.title || attachment.filename
                    };
                });

                if (type === 'featured') {
                    onChange(selectedImages);
                } else {
                    onChange([...images, ...selectedImages]);
                }

                showSuccess(`${selectedImages.length} image(s) selected successfully`);
            });

            frame.open();
        } else {
            showError('WordPress Media Library is not available');
        }
    };

    const handleFileSelect = async (e) => {
        const files = Array.from(e.target.files);

        if (files.length === 0) return;

        // Validate file types
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
        const invalidFiles = files.filter(file => !validTypes.includes(file.type));

        if (invalidFiles.length > 0) {
            showError('Please select only image files (JPEG, PNG, GIF, WebP)');
            return;
        }

        // Validate file sizes (max 5MB per file)
        const maxSize = 5 * 1024 * 1024; // 5MB
        const oversizedFiles = files.filter(file => file.size > maxSize);

        if (oversizedFiles.length > 0) {
            showError('Some files are too large. Maximum size is 5MB per image');
            return;
        }

        try {
            setUploading(true);

            const uploadPromises = files.map(async (file) => {
                const formData = new FormData();
                formData.append('file', file);

                const response = await api.uploadProductImage(formData);
                if (response.success) {
                    return {
                        id: response.attachment_id || Date.now(),
                        src: response.url,
                        alt: response.alt || '',
                        name: response.title || file.name
                    };
                }
                throw new Error(response.message || 'Upload failed');
            });

            const uploadedImages = await Promise.all(uploadPromises);

            if (type === 'featured') {
                // For featured image, replace existing
                onChange(uploadedImages);
            } else {
                // For gallery, append to existing
                onChange([...images, ...uploadedImages]);
            }

            showSuccess(`${uploadedImages.length} image(s) uploaded successfully`);
        } catch (error) {
            console.error('Error uploading images:', error);
            showError(error.message || 'Failed to upload images');
        } finally {
            setUploading(false);
        }
    };

    const handleRemoveImage = (imageId) => {
        onChange(images.filter(img => img.id !== imageId));
    };

    const handleSetFeatured = (image) => {
        // Move selected image to first position
        const otherImages = images.filter(img => img.id !== image.id);
        onChange([image, ...otherImages]);
    };

    if (type === 'featured') {
        const featuredImage = images[0];

        return (
            <div className="image-uploader featured-uploader">
                {featuredImage ? (
                    <div className="featured-image-preview">
                        <img src={featuredImage.src} alt={featuredImage.alt || 'Featured'} />
                        <div className="image-actions">
                            <button
                                type="button"
                                className="btn-image-action"
                                onClick={() => handleRemoveImage(featuredImage.id)}
                                title="Remove image"
                            >
                                🗑️
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="upload-placeholder">
                        <div className="upload-icon">📷</div>
                        <p>No image set</p>
                    </div>
                )}

                <div className="upload-buttons" style={{ marginTop: '12px', display: 'flex', gap: '8px' }}>
                    <label className="btn btn-secondary btn-sm" style={{ flex: 1 }}>
                        {uploading ? 'Uploading...' : '📤 Upload'}
                        <input
                            type="file"
                            accept="image/*"
                            onChange={handleFileSelect}
                            disabled={uploading}
                            style={{ display: 'none' }}
                        />
                    </label>
                    <button
                        type="button"
                        className="btn btn-secondary btn-sm"
                        onClick={openMediaLibrary}
                        disabled={uploading}
                        style={{ flex: 1 }}
                    >
                        🖼️ Media Library
                    </button>
                </div>
            </div>
        );
    }

    // Gallery mode
    return (
        <div className="image-uploader gallery-uploader">
            {images.length > 0 && (
                <div className="gallery-grid">
                    {images.map((image, index) => (
                        <div key={image.id} className="gallery-item">
                            <img src={image.src} alt={image.alt || `Gallery ${index + 1}`} />
                            <div className="image-actions">
                                {index !== 0 && (
                                    <button
                                        type="button"
                                        className="btn-image-action"
                                        onClick={() => handleSetFeatured(image)}
                                        title="Set as featured"
                                    >
                                        ⭐
                                    </button>
                                )}
                                <button
                                    type="button"
                                    className="btn-image-action"
                                    onClick={() => handleRemoveImage(image.id)}
                                    title="Remove image"
                                >
                                    🗑️
                                </button>
                            </div>
                            {index === 0 && (
                                <div className="featured-badge">Featured</div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            <div className="upload-buttons" style={{ marginTop: images.length > 0 ? '12px' : 0, display: 'flex', gap: '8px' }}>
                <label className="btn btn-secondary btn-sm" style={{ flex: 1 }}>
                    {uploading ? 'Uploading...' : '📤 Upload Images'}
                    <input
                        type="file"
                        accept="image/*"
                        multiple
                        onChange={handleFileSelect}
                        disabled={uploading}
                        style={{ display: 'none' }}
                    />
                </label>
                <button
                    type="button"
                    className="btn btn-secondary btn-sm"
                    onClick={openMediaLibrary}
                    disabled={uploading}
                    style={{ flex: 1 }}
                >
                    🖼️ Media Library
                </button>
            </div>

            {images.length === 0 && (
                <p style={{ fontSize: '12px', color: '#6b7280', marginTop: '8px', textAlign: 'center' }}>
                    Upload product images. First image will be the featured image.
                </p>
            )}
        </div>
    );
};

export default ImageUploader;
