// ProfilePhotoUpload Component
// Editable profile photo with upload, preview, and validation

function ProfilePhotoUpload({ currentPhotoUrl, userName, onPhotoUpdate, token }) {
    const [uploading, setUploading] = useState(false);
    const [preview, setPreview] = useState(null);
    const [error, setError] = useState(null);
    const [success, setSuccess] = useState(false);
    const fileInputRef = React.useRef(null);

    const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];

    const handleFileSelect = async (file) => {
        setError(null);
        setSuccess(false);

        // Validate file type
        if (!ALLOWED_TYPES.includes(file.type)) {
            setError('Please upload an image file (PNG, JPG, GIF, WebP)');
            return;
        }

        // Validate file size
        if (file.size > MAX_FILE_SIZE) {
            setError('File size must be under 5MB');
            return;
        }

        // Show preview
        const reader = new FileReader();
        reader.onloadend = () => setPreview(reader.result);
        reader.readAsDataURL(file);

        // Upload immediately
        await uploadPhoto(file);
    };

    const uploadPhoto = async (file) => {
        setUploading(true);
        setError(null);

        try {
            const formData = new FormData();
            formData.append('photo', file);

            const response = await fetch(`${API_URL}/profile/photo`, {
                method: 'PATCH',
                headers: { 'Authorization': `Bearer ${token}` },
                body: formData
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.detail || 'Upload failed');
            }

            setSuccess(true);
            setPreview(null);

            // Notify parent component
            if (onPhotoUpdate) {
                onPhotoUpdate(data.photo_url);
            }

            setTimeout(() => setSuccess(false), 3000);

        } catch (err) {
            setError(err.message);
        } finally {
            setUploading(false);
        }
    };

    const handleRemovePhoto = async () => {
        if (!confirm('Remove your profile photo?')) return;

        setUploading(true);
        setError(null);

        try {
            const response = await fetch(`${API_URL}/profile/photo`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.detail || 'Failed to remove photo');
            }

            if (onPhotoUpdate) {
                onPhotoUpdate(null);
            }

            setSuccess(true);
            setTimeout(() => setSuccess(false), 3000);

        } catch (err) {
            setError(err.message);
        } finally {
            setUploading(false);
        }
    };

    return (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
            {/* Photo Display */}
            <div style={{ position: 'relative' }}>
                <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/png,image/jpeg,image/jpg,image/gif,image/webp"
                    style={{ display: 'none' }}
                    onChange={(e) => {
                        const file = e.target.files[0];
                        if (file) handleFileSelect(file);
                    }}
                />

                <div
                    onClick={() => fileInputRef.current?.click()}
                    style={{
                        cursor: 'pointer',
                        position: 'relative',
                        transition: 'opacity 0.2s'
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.opacity = '0.8'}
                    onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
                >
                    <ProfilePhoto
                        photoUrl={preview ? null : currentPhotoUrl}
                        userName={userName}
                        size="large"
                        showStatus={false}
                    />
                    {preview && (
                        <div style={{
                            width: '80px',
                            height: '80px',
                            borderRadius: '50%',
                            overflow: 'hidden',
                            position: 'absolute',
                            top: 0,
                            left: 0
                        }}>
                            <img src={preview} alt="Preview" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                        </div>
                    )}

                    {/* Upload overlay */}
                    <div style={{
                        position: 'absolute',
                        bottom: 0,
                        right: 0,
                        background: 'var(--primary)',
                        color: 'white',
                        borderRadius: '50%',
                        width: '28px',
                        height: '28px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: '16px',
                        border: '2px solid var(--bg-primary)',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
                    }}>
                        📷
                    </div>
                </div>
            </div>

            {/* Action Buttons */}
            <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', justifyContent: 'center' }}>
                <button
                    onClick={() => fileInputRef.current?.click()}
                    disabled={uploading}
                    style={{
                        background: 'var(--primary)',
                        color: 'white',
                        border: 'none',
                        borderRadius: '6px',
                        padding: '0.4rem 0.85rem',
                        fontSize: '0.75rem',
                        fontWeight: '600',
                        cursor: uploading ? 'not-allowed' : 'pointer',
                        opacity: uploading ? 0.6 : 1,
                        display: 'flex',
                        alignItems: 'center',
                        gap: '0.375rem',
                        transition: 'all 0.2s ease',
                        boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
                    }}
                    onMouseEnter={(e) => {
                        if (!uploading) {
                            e.currentTarget.style.transform = 'translateY(-1px)';
                            e.currentTarget.style.boxShadow = '0 2px 6px rgba(0,0,0,0.15)';
                        }
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.transform = 'translateY(0)';
                        e.currentTarget.style.boxShadow = '0 1px 3px rgba(0,0,0,0.1)';
                    }}
                >
                    <span style={{ fontSize: '0.875rem' }}>📷</span>
                    {currentPhotoUrl ? 'Change' : 'Upload'}
                </button>

                {currentPhotoUrl && (
                    <button
                        onClick={handleRemovePhoto}
                        disabled={uploading}
                        style={{
                            background: 'transparent',
                            color: 'var(--error)',
                            border: '1.5px solid var(--error)',
                            borderRadius: '6px',
                            padding: '0.4rem 0.85rem',
                            fontSize: '0.75rem',
                            fontWeight: '600',
                            cursor: uploading ? 'not-allowed' : 'pointer',
                            opacity: uploading ? 0.6 : 1,
                            display: 'flex',
                            alignItems: 'center',
                            gap: '0.375rem',
                            transition: 'all 0.2s ease'
                        }}
                        onMouseEnter={(e) => {
                            if (!uploading) {
                                e.currentTarget.style.background = 'var(--error)';
                                e.currentTarget.style.color = 'white';
                            }
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'transparent';
                            e.currentTarget.style.color = 'var(--error)';
                        }}
                    >
                        <span style={{ fontSize: '0.875rem' }}>🗑️</span>
                        Remove
                    </button>
                )}
            </div>

            {/* Status Messages */}
            {uploading && (
                <div style={{
                    fontSize: '0.875rem',
                    color: 'var(--primary)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.5rem'
                }}>
                    <span className="spinner"></span> Uploading...
                </div>
            )}

            {error && (
                <div style={{
                    fontSize: '0.875rem',
                    color: 'var(--danger)',
                    padding: '0.5rem 1rem',
                    background: 'var(--danger-light)',
                    borderRadius: '0.5rem',
                    maxWidth: '300px',
                    textAlign: 'center'
                }}>
                    {error}
                </div>
            )}

            {success && (
                <div style={{
                    fontSize: '0.875rem',
                    color: 'var(--success)',
                    padding: '0.5rem 1rem',
                    background: 'var(--success-light)',
                    borderRadius: '0.5rem',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.5rem'
                }}>
                    ✓ Photo updated successfully!
                </div>
            )}

            {/* Hint Text */}
            {/* <p style={{
                fontSize: '0.75rem',
                color: 'var(--text-secondary)',
                textAlign: 'center',
                maxWidth: '300px',
                margin: 0
            }}>
                Click to upload or change your photo. Max 5MB. Formats: PNG, JPG, GIF, WebP
            </p> */}
        </div>
    );
}

// Export to global scope
window.ProfilePhotoUpload = ProfilePhotoUpload;
