import React, { useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Image, Upload } from 'lucide-react';
import { __ } from '@/lib/i18n';

interface MediaUploaderProps {
    onSelect: (url: string, id?: number) => void;
    type?: 'image' | 'video' | 'audio' | 'file';
    title?: string;
    buttonText?: string;
    className?: string;
    children?: React.ReactNode;
}

export function MediaUploader({
    onSelect,
    type = 'image',
    title = __('Select Image'),
    buttonText = __('Use Image'),
    className,
    children
}: MediaUploaderProps) {
    const frameRef = useRef<any>(null);

    const openMediaModal = (e: React.MouseEvent) => {
        e.preventDefault();

        // Check if wp.media is available
        const wp = (window as any).wp;
        if (!wp || !wp.media) {
            console.warn('WordPress media library not available');
            return;
        }

        // Reuse existing frame
        if (frameRef.current) {
            frameRef.current.open();
            return;
        }

        // Create new frame
        frameRef.current = wp.media({
            title,
            button: {
                text: buttonText,
            },
            library: {
                type,
            },
            multiple: false,
        });

        // Handle selection
        frameRef.current.on('select', () => {
            const state = frameRef.current.state();
            const selection = state.get('selection');

            if (selection.length > 0) {
                const attachment = selection.first().toJSON();
                onSelect(attachment.url, attachment.id);
            }
        });

        frameRef.current.open();
    };

    return (
        <div onClick={openMediaModal} className={className}>
            {children || (
                <Button variant="outline" size="sm" type="button">
                    <Upload className="w-4 h-4 mr-2" />
                    {__('Select Image')}
                </Button>
            )}
        </div>
    );
}
