import React, { useState } from 'react';

const ImageInput = ({ onImageSelected, onAnalyze, isLoading, hasResult }) => {
    const [preview, setPreview] = useState(null);
    const [fileName, setFileName] = useState('');

    const handleFileChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setFileName(file.name);
            const reader = new FileReader();
            reader.onloadend = () => {
                const base64String = reader.result;
                setPreview(base64String);
                // Extract the raw base64 string (remove "data:image/jpeg;base64," prefix)
                const rawBase64 = base64String.split(',')[1];
                onImageSelected(rawBase64);
            };
            reader.readAsDataURL(file);
        }
    };

    return (
        <div className="card">
            <div className="input-group" style={{ flexDirection: 'column', gap: '1rem' }}>
                <div className="file-input-wrapper">
                    <input
                        type="file"
                        accept="image/*"
                        onChange={handleFileChange}
                        disabled={isLoading}
                        className="file-input"
                        id="file-upload"
                    />
                    <label htmlFor="file-upload" className="file-input-label">
                        <span>Choose Products Shelf Image(jpg)</span>
                        {fileName || 'No image chosen'}
                    </label>
                </div>

                {preview && (
                    <div className="image-preview" style={{ textAlign: 'center' }}>
                        <img
                            src={preview}
                            alt="Preview"
                            style={{ maxWidth: '100%', maxHeight: '400px', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}
                        />
                    </div>
                )}

                <button
                    onClick={onAnalyze}
                    disabled={isLoading || !preview || hasResult}
                    style={{ width: '100%' }}
                >
                    {isLoading ? <div className="loading-spinner" /> : 'Analyze Shelf'}
                </button>
            </div>
        </div>
    );
};

export default ImageInput;
