// ============================================================================
// REAL ESTATE VIEW - Gestion des annonces immobilières
// ============================================================================

const RealEstateView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [realEstates, setRealEstates] = useState([]);
    const [screens, setScreens] = useState([]);
    const [configurations, setConfigurations] = useState([]);
    const [selectedConfig, setSelectedConfig] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingRealEstate, setEditingRealEstate] = useState(null);
    const [uploading, setUploading] = useState(false);

    // Form state
    const [formListingType, setFormListingType] = useState('rent');
    const [formPropertyType, setFormPropertyType] = useState('Appartement');
    const [formRooms, setFormRooms] = useState('');
    const [formAddress, setFormAddress] = useState('');
    const [formCity, setFormCity] = useState('');
    const [formPostalCode, setFormPostalCode] = useState('');
    const [formPrice, setFormPrice] = useState('');
    const [formPriceExclVat, setFormPriceExclVat] = useState(false);
    const [formAvailableFrom, setFormAvailableFrom] = useState('');
    const [formImageUrl, setFormImageUrl] = useState('');
    const [formSurface, setFormSurface] = useState('');
    const [formFloor, setFormFloor] = useState('');
    const [formDescription, setFormDescription] = useState('');
    const [formScreenId, setFormScreenId] = useState(null);
    const [formConfigurationId, setFormConfigurationId] = useState(null);
    const [formIsActive, setFormIsActive] = useState(true);

    useEffect(() => {
        loadRealEstates();
        loadScreens();
        loadConfigurations();
    }, []);

    const loadRealEstates = async () => {
        setLoading(true);
        try {
            const result = await api.getRealEstates(customer.id);
            console.log('🏢 Annonces chargées:', result);
            setRealEstates(result.real_estates || []);
        } catch (error) {
            console.error('Erreur chargement annonces:', error);
            toast.error('Erreur lors du chargement des annonces');
        }
        setLoading(false);
    };

    const loadScreens = async () => {
        try {
            const result = await api.getScreens(customer.id);
            setScreens(result.screens || []);
        } catch (error) {
            console.error('Erreur chargement écrans:', error);
        }
    };

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            const configs = result.configurations || [];
            setConfigurations(configs);
            // Sélectionner automatiquement la première configuration
            if (configs.length > 0 && !selectedConfig) {
                setSelectedConfig(configs[0].id);
            }
        } catch (error) {
            console.error('Erreur chargement configurations:', error);
        }
    };

    // Filtrer les annonces par configuration
    const filteredRealEstates = realEstates.filter(re => {
        return re.configuration_id == selectedConfig || re.screen_id;
    });

    // Configuration actuelle
    const currentConfig = configurations.find(c => c.id == selectedConfig);

    const handleFileUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (!file.type.startsWith('image/')) {
            toast.error('Seules les images sont acceptées');
            return;
        }

        setUploading(true);
        try {
            console.log('📤 Upload en cours:', file.name);
            const result = await api.uploadFile(file);
            if (result.url) {
                setFormImageUrl(result.url);
                toast.success('Image uploadée avec succès');
                console.log('✅ Image uploadée:', result.url);
            }
        } catch (error) {
            console.error('❌ Erreur upload:', error);
            toast.error('Erreur lors de l\'upload');
        }
        setUploading(false);
    };

    const openModal = (realEstate = null) => {
        if (realEstate) {
            // Mode édition
            setEditingRealEstate(realEstate);
            setFormListingType(realEstate.listing_type);
            setFormPropertyType(realEstate.property_type || 'Appartement');
            setFormRooms(realEstate.rooms);
            setFormAddress(realEstate.address);
            setFormCity(realEstate.city || '');
            setFormPostalCode(realEstate.postal_code || '');
            setFormPrice(realEstate.price);
            setFormPriceExclVat(realEstate.price_excl_vat == 1);
            setFormAvailableFrom(realEstate.available_from);
            setFormImageUrl(realEstate.image_url || '');
            setFormSurface(realEstate.surface || '');
            setFormFloor(realEstate.floor || '');
            setFormDescription(realEstate.description || '');
            setFormScreenId(realEstate.screen_id);
            setFormConfigurationId(realEstate.configuration_id);
            setFormIsActive(realEstate.is_active == 1);
        } else {
            // Mode création
            setEditingRealEstate(null);
            resetForm();
        }
        setIsModalOpen(true);
    };

    const closeModal = () => {
        setIsModalOpen(false);
        setEditingRealEstate(null);
        resetForm();
    };

    const resetForm = () => {
        setFormListingType('rent');
        setFormPropertyType('Appartement');
        setFormRooms('');
        setFormAddress('');
        setFormCity('');
        setFormPostalCode('');
        setFormPrice('');
        setFormPriceExclVat(false);
        setFormAvailableFrom('');
        setFormImageUrl('');
        setFormSurface('');
        setFormFloor('');
        setFormDescription('');
        setFormScreenId(null);
        setFormConfigurationId(null);
        setFormIsActive(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!formScreenId && !formConfigurationId) {
            toast.error('Veuillez sélectionner un écran ou une configuration');
            return;
        }

        if (!formImageUrl || formImageUrl.trim() === '') {
            toast.error('Veuillez uploader une image pour l\'annonce');
            return;
        }

        const data = {
            customer_id: customer.id,
            listing_type: formListingType,
            property_type: formPropertyType,
            rooms: (formPropertyType === 'Appartement' || formPropertyType === 'Maison') ? parseFloat(formRooms) : null,
            address: formAddress,
            city: formCity,
            postal_code: formPostalCode,
            price: parseFloat(formPrice),
            price_excl_vat: formPriceExclVat ? 1 : 0,
            available_from: formAvailableFrom,
            image_url: formImageUrl,
            surface: (formPropertyType === 'Appartement' || formPropertyType === 'Maison') ? (formSurface ? parseInt(formSurface) : null) : null,
            floor: formPropertyType === 'Appartement' ? formFloor : null,
            description: formDescription,
            screen_id: formScreenId,
            configuration_id: formConfigurationId,
            is_active: formIsActive ? 1 : 0
        };

        try {
            if (editingRealEstate) {
                const result = await api.updateRealEstate(editingRealEstate.id, data);
                if (result.message) {
                    toast.success('Annonce mise à jour');
                    loadRealEstates();
                    closeModal();
                }
            } else {
                const result = await api.createRealEstate(data);
                if (result.real_estate_id) {
                    toast.success('Annonce créée');
                    loadRealEstates();
                    closeModal();
                }
            }
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const handleDelete = async (realEstateId) => {
        if (!confirm('Êtes-vous sûr de vouloir supprimer cette annonce ?')) return;

        try {
            const result = await api.deleteRealEstate(realEstateId);
            if (result.message) {
                toast.success('Annonce supprimée');
                loadRealEstates();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    const getRoomLabel = (rooms) => {
        if (rooms === 1) return '1 pièce';
        if (rooms % 1 === 0) return `${rooms} pièces`;
        return `${rooms} pièces`;
    };

    const formatPrice = (price, listingType) => {
        const formatted = new Intl.NumberFormat('fr-CH', {
            style: 'currency',
            currency: 'CHF'
        }).format(price);
        
        return listingType === 'rent' ? `${formatted}/mois` : formatted;
    };

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        return date.toLocaleDateString('fr-CH', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric'
        });
    };

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
                        <i className="fas fa-building text-purple-600"></i>
                        Annonces Immobilières
                    </h2>
                    <p className="text-gray-600 text-sm mt-1">
                        Gérez les annonces immobilières de votre régie
                    </p>
                </div>
                <Button 
                    onClick={() => openModal()}
                    variant="primary"
                    icon="fa-plus"
                >
                    Nouvelle annonce
                </Button>
            </div>

            {/* Sélecteur de configuration */}
            <Card id="sm-realestate-config-selector" className="sm-config-selector">
                <div className="flex items-center gap-4">
                    <label className="font-semibold text-gray-700">Configuration :</label>
                    <select
                        value={selectedConfig || ''}
                        onChange={(e) => setSelectedConfig(parseInt(e.target.value))}
                        className="px-4 py-2 border border-gray-300 rounded-lg flex-1"
                    >
                        {configurations.map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </select>
                    {currentConfig && (
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                            <i className="fas fa-tv"></i>
                            <span>{currentConfig.screens_count} écran(s) utilisent cette configuration</span>
                        </div>
                    )}
                </div>
            </Card>

            {/* Loader */}
            {loading && (
                <div className="flex items-center justify-center py-12">
                    <Loader />
                </div>
            )}

            {/* Liste des annonces */}
            {!loading && filteredRealEstates.length === 0 && (
                <EmptyState
                    icon="fa-building"
                    title="Aucune annonce immobilière"
                    description="Créez votre première annonce pour l'afficher sur vos écrans"
                    actionLabel="Créer une annonce"
                    onAction={() => openModal()}
                />
            )}

            {!loading && filteredRealEstates.length > 0 && (
                <div id="sm-realestate-list" className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                    <table className="w-full">
                            <thead className="bg-gray-50 border-b-2 border-gray-200">
                                <tr>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Photo
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Type
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Adresse
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Détails
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Affichage
                                    </th>
                                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Statut
                                    </th>
                                    <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase tracking-wider">
                                        Actions
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200 bg-white">
                                {filteredRealEstates.map(realEstate => (
                                    <tr 
                                        key={realEstate.id} 
                                        className="hover:bg-gray-50 transition-colors"
                                        id={`sm-realestate-row-${realEstate.id}`}
                                    >
                                        {/* Photo */}
                                        <td className="px-4 py-3">
                                            <div className="w-20 h-20 rounded-lg overflow-hidden">
                                                {realEstate.image_url ? (
                                                    <img 
                                                        src={realEstate.image_url} 
                                                        alt="Annonce" 
                                                        className="w-full h-full object-cover"
                                                    />
                                                ) : (
                                                    <div className="w-full h-full bg-gradient-to-br from-purple-100 to-blue-100 flex items-center justify-center">
                                                        <i className="fas fa-building text-2xl text-purple-300"></i>
                                                    </div>
                                                )}
                                            </div>
                                        </td>

                                        {/* Type */}
                                        <td className="px-4 py-3">
                                            <span className={`px-3 py-1 rounded-full text-white text-xs font-semibold ${
                                                realEstate.listing_type === 'rent' 
                                                    ? 'bg-blue-500' 
                                                    : 'bg-green-500'
                                            }`}>
                                                {realEstate.listing_type === 'rent' ? 'À LOUER' : 'À VENDRE'}
                                            </span>
                                        </td>

                                        {/* Adresse */}
                                        <td className="px-4 py-3">
                                            <div className="text-sm text-gray-900 font-medium">
                                                {realEstate.address}
                                            </div>
                                            {realEstate.city && (
                                                <div className="text-xs text-gray-500 mt-1">
                                                    {realEstate.postal_code} {realEstate.city}
                                                </div>
                                            )}
                                            <div className="text-xs text-gray-500 mt-1 flex items-center gap-3">
                                                <span>{getRoomLabel(realEstate.rooms)}</span>
                                                {realEstate.surface && (
                                                    <>
                                                        <span>•</span>
                                                        <span>{realEstate.surface} m²</span>
                                                    </>
                                                )}
                                            </div>
                                        </td>

                                        {/* Détails (prix, disponibilité) */}
                                        <td className="px-4 py-3">
                                            <div className="space-y-2 text-sm">
                                                {/* Prix */}
                                                <div className="flex items-center gap-2 text-purple-600 font-bold">
                                                    <i className="fas fa-tag text-purple-500"></i>
                                                    <span>{formatPrice(realEstate.price, realEstate.listing_type)}</span>
                                                </div>
                                                
                                                {/* Disponibilité */}
                                                <div className="flex items-center gap-2 text-gray-600">
                                                    <i className="fas fa-calendar text-green-500"></i>
                                                    <span>{formatDate(realEstate.available_from)}</span>
                                                </div>
                                            </div>
                                        </td>

                                        {/* Affichage (écran ou config) */}
                                        <td className="px-4 py-3">
                                            <div className="flex items-center gap-2 text-xs text-gray-600">
                                                {realEstate.screen_id ? (
                                                    <>
                                                        <i className="fas fa-tv text-blue-500"></i>
                                                        <span>
                                                            {screens.find(s => s.id == realEstate.screen_id)?.label || `Écran #${realEstate.screen_id}`}
                                                        </span>
                                                    </>
                                                ) : (
                                                    <>
                                                        <i className="fas fa-cog text-gray-500"></i>
                                                        <span>
                                                            {configurations.find(c => c.id == realEstate.configuration_id)?.name || `Config #${realEstate.configuration_id}`}
                                                        </span>
                                                    </>
                                                )}
                                            </div>
                                        </td>

                                        {/* Statut */}
                                        <td className="px-4 py-3">
                                            <span className={realEstate.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                                {realEstate.is_active == 1 ? 'Active' : 'Inactive'}
                                            </span>
                                        </td>

                                        {/* Actions */}
                                        <td className="px-4 py-3">
                                            <div className="flex items-center justify-center gap-2">
                                                <button
                                                    onClick={() => openModal(realEstate)}
                                                    className="px-3 py-1.5 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-all"
                                                    title="Modifier"
                                                >
                                                    <i className="fas fa-edit"></i>
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(realEstate.id)}
                                                    className="px-3 py-1.5 bg-red-500 text-white text-sm rounded hover:bg-red-600 transition-all"
                                                    title="Supprimer"
                                                >
                                                    <i className="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                </div>
            )}

            {/* Modal d'ajout/édition */}
            <Modal
                id="sm-realestate-modal"
                isOpen={isModalOpen}
                onClose={closeModal}
                title={editingRealEstate ? 'Modifier l\'annonce' : 'Nouvelle annonce immobilière'}
                size="md"
            >
                <form id="sm-realestate-form" className="sm-form space-y-4" onSubmit={handleSubmit}>
                    {/* Type d'annonce */}
                    <Select
                        id="sm-realestate-select-type"
                        label="Type d'annonce"
                        value={formListingType}
                        onChange={setFormListingType}
                        required
                        icon="fa-tag"
                    >
                        <option value="rent">À louer</option>
                        <option value="sale">À vendre</option>
                    </Select>

                    {/* Type de propriété */}
                    <Select
                        id="sm-realestate-select-property-type"
                        label="Type de bien"
                        value={formPropertyType}
                        onChange={setFormPropertyType}
                        required
                        icon="fa-building"
                    >
                        <option value="Appartement">Appartement</option>
                        <option value="Maison">Maison</option>
                        <option value="Place de parking intérieur">Place de parking intérieur</option>
                        <option value="Place de parking extérieur">Place de parking extérieur</option>
                        <option value="Autre">Autre</option>
                    </Select>

                    {/* Nombre de pièces et Surface - Uniquement pour Appartement ou Maison */}
                    {(formPropertyType === 'Appartement' || formPropertyType === 'Maison') && (
                        <div id="sm-realestate-row-rooms-surface" className="sm-form-row grid grid-cols-2 gap-4">
                            <Input
                                id="sm-realestate-input-rooms"
                                label="Nombre de pièces"
                                type="number"
                                step="0.5"
                                value={formRooms}
                                onChange={setFormRooms}
                                placeholder="Ex: 2.5, 3.5, 4.5"
                                required
                                icon="fa-door-open"
                            />
                            <Input
                                id="sm-realestate-input-surface"
                                label="Surface (m²)"
                                type="number"
                                value={formSurface}
                                onChange={setFormSurface}
                                placeholder="Ex: 85"
                                icon="fa-ruler-combined"
                            />
                        </div>
                    )}

                    {/* Adresse avec autocomplétion */}
                    <AddressAutocomplete
                        id="sm-realestate-input-address"
                        label="Adresse (rue et numéro)"
                        value={formAddress}
                        onAddressSelected={(data) => {
                            // Séparer l'adresse complète
                            const addressParts = data.address.split(',').map(part => part.trim());
                            
                            // La première partie = rue + numéro
                            const streetAndNumber = addressParts[0] || '';
                            setFormAddress(streetAndNumber);
                            
                            // Extraire ville et code postal (avant le pays)
                            if (addressParts.length >= 2) {
                                // Prendre l'avant-dernière partie (avant "Switzerland")
                                const cityPostal = addressParts[addressParts.length - 2];
                                const postalMatch = cityPostal.match(/(\d{4})\s+(.+)/);
                                if (postalMatch) {
                                    setFormPostalCode(postalMatch[1]);
                                    setFormCity(postalMatch[2]);
                                }
                            }
                        }}
                        placeholder="Ex: Route de Chancy 10"
                        required
                    />

                    {/* Ville et Code postal */}
                    <div id="sm-realestate-row-city-postal" className="sm-form-row grid grid-cols-2 gap-4">
                        <Input
                            id="sm-realestate-input-city"
                            label="Ville"
                            value={formCity}
                            onChange={setFormCity}
                            placeholder="Genève"
                            icon="fa-city"
                        />
                        <Input
                            id="sm-realestate-input-postal"
                            label="Code postal"
                            value={formPostalCode}
                            onChange={setFormPostalCode}
                            placeholder="1200"
                            icon="fa-mail-bulk"
                        />
                    </div>

                    {/* Prix et Étage */}
                    <div id="sm-realestate-row-price-floor" className="sm-form-row grid grid-cols-2 gap-4">
                        <Input
                            id="sm-realestate-input-price"
                            label={formListingType === 'rent' ? 'Prix mensuel (CHF)' : 'Prix de vente (CHF)'}
                            type="number"
                            step="0.01"
                            value={formPrice}
                            onChange={setFormPrice}
                            placeholder={formListingType === 'rent' ? '2500' : '850000'}
                            required
                            icon="fa-money-bill-wave"
                        />
                        {/* Étage - Uniquement pour Appartement */}
                        {formPropertyType === 'Appartement' ? (
                            <Input
                                id="sm-realestate-input-floor"
                                label="Étage"
                                value={formFloor}
                                onChange={setFormFloor}
                                placeholder="3ème, RDC, etc."
                                icon="fa-layer-group"
                            />
                        ) : (
                            <div></div>
                        )}
                    </div>

                    {/* Prix hors TVA - Checkbox uniquement pour locations */}
                    {formListingType === 'rent' && (
                        <div id="sm-realestate-checkbox-vat" className="flex items-center gap-3 p-4 bg-blue-50 rounded-lg border border-blue-200">
                            <input
                                type="checkbox"
                                id="sm-realestate-checkbox-excl-vat"
                                checked={formPriceExclVat}
                                onChange={(e) => setFormPriceExclVat(e.target.checked)}
                                className="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                            />
                            <label htmlFor="sm-realestate-checkbox-excl-vat" className="text-sm font-medium text-gray-700 cursor-pointer">
                                <i className="fas fa-percent text-blue-600 mr-2"></i>
                                Prix hors TVA
                            </label>
                        </div>
                    )}

                    {/* Date de disponibilité */}
                    <Input
                        id="sm-realestate-input-available"
                        label="Disponible dès le"
                        type="date"
                        value={formAvailableFrom}
                        onChange={setFormAvailableFrom}
                        required
                        icon="fa-calendar"
                    />

                    {/* Upload d'image */}
                    <div id="sm-realestate-upload-group" className="sm-form-group mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            <i className="fas fa-image mr-2"></i>
                            Image de l'annonce <span className="text-red-500">*</span>
                        </label>
                        <div 
                            id="sm-realestate-upload-zone"
                            className="sm-upload-zone upload-zone p-6 text-center cursor-pointer" 
                            onClick={() => document.getElementById('sm-realestate-file-input').click()}
                        >
                            {formImageUrl ? (
                                <div id="sm-realestate-preview-container" className="sm-upload-preview">
                                    <img 
                                        id="sm-realestate-preview-image"
                                        src={formImageUrl} 
                                        alt="Preview" 
                                        className="max-h-48 mx-auto mb-2 rounded-lg object-cover" 
                                    />
                                    <p className="text-sm text-green-600">
                                        <i className="fas fa-check-circle mr-1"></i>
                                        Image uploadée
                                    </p>
                                    <p className="text-xs text-gray-500 mt-1">
                                        Cliquez pour changer l'image
                                    </p>
                                </div>
                            ) : (
                                <div id="sm-realestate-upload-placeholder">
                                    <i className="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                                    <p className="text-gray-600">Cliquez pour uploader une image</p>
                                    <p className="text-xs text-gray-400 mt-1">JPG, PNG (max 5MB)</p>
                                </div>
                            )}
                            {uploading && (
                                <div id="sm-realestate-upload-progress" className="mt-2">
                                    <i className="fas fa-spinner fa-spin text-orange-500 mr-2"></i>
                                    <span className="text-sm text-orange-500">Upload en cours...</span>
                                </div>
                            )}
                        </div>
                        <input
                            id="sm-realestate-file-input"
                            type="file"
                            accept="image/*"
                            onChange={handleFileUpload}
                            className="hidden"
                        />
                        <p className="text-xs text-gray-500 mt-2">
                            💡 Les images sont automatiquement uploadées sur SwissApp Files
                        </p>
                    </div>

                    {/* Description */}
                    <div id="sm-realestate-description-group" className="sm-form-group">
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            <i className="fas fa-align-left mr-2"></i>
                            Description
                        </label>
                        <textarea
                            id="sm-realestate-textarea-description"
                            value={formDescription}
                            onChange={(e) => setFormDescription(e.target.value)}
                            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                            rows="3"
                            placeholder="Description du bien..."
                        />
                    </div>

                    {/* Écran ou Configuration */}
                    <div id="sm-realestate-row-screen-config" className="sm-form-row grid grid-cols-2 gap-4">
                        <Select
                            id="sm-realestate-select-screen"
                            label="Écran"
                            value={formScreenId || ''}
                            onChange={(value) => {
                                setFormScreenId(value || null);
                                if (value) setFormConfigurationId(null);
                            }}
                            icon="fa-tv"
                            helpText="OU Configuration"
                        >
                            <option value="">Aucun (utiliser config)</option>
                            {screens.map(screen => (
                                <option key={screen.id} value={screen.id}>
                                    {screen.label}
                                </option>
                            ))}
                        </Select>

                        <Select
                            id="sm-realestate-select-config"
                            label="Configuration"
                            value={formConfigurationId || ''}
                            onChange={(value) => {
                                setFormConfigurationId(value || null);
                                if (value) setFormScreenId(null);
                            }}
                            icon="fa-cog"
                            helpText="OU Écran"
                        >
                            <option value="">Aucune (utiliser écran)</option>
                            {configurations.map(config => (
                                <option key={config.id} value={config.id}>
                                    {config.name}
                                </option>
                            ))}
                        </Select>
                    </div>

                    {/* Statut actif */}
                    <div id="sm-realestate-checkbox-group" className="sm-form-group">
                        <label className="flex items-center gap-3 cursor-pointer">
                            <input
                                id="sm-realestate-checkbox-active"
                                type="checkbox"
                                checked={formIsActive}
                                onChange={(e) => setFormIsActive(e.target.checked)}
                                className="w-5 h-5 text-purple-600 rounded focus:ring-2 focus:ring-purple-500"
                            />
                            <span className="text-sm font-medium text-gray-700">
                                Annonce active
                            </span>
                        </label>
                    </div>

                    {/* Boutons */}
                    <div id="sm-realestate-actions" className="sm-modal-actions flex gap-3 pt-4">
                        <Button 
                            id="sm-realestate-btn-cancel"
                            type="button" 
                            onClick={closeModal} 
                            variant="secondary"
                            className="flex-1"
                        >
                            Annuler
                        </Button>
                        <Button 
                            id="sm-realestate-btn-save"
                            variant="primary" 
                            className="flex-1"
                            disabled={!formImageUrl || uploading}
                        >
                            {uploading ? (
                                <>
                                    <i className="fas fa-spinner fa-spin mr-2"></i>
                                    Upload...
                                </>
                            ) : (
                                editingRealEstate ? 'Enregistrer' : 'Créer'
                            )}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

