// ============================================================================
// VUE CONFIGURATIONS
// ============================================================================

const ConfigurationsView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [configurations, setConfigurations] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingConfig, setEditingConfig] = useState(null);

    // Form state
    const [formName, setFormName] = useState('');
    const [formDescription, setFormDescription] = useState('');
    const [formActive, setFormActive] = useState(true);
    const [formSigConnectEnabled, setFormSigConnectEnabled] = useState(false);

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

    const loadConfigurations = async () => {
        setLoading(true);
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations) {
                setConfigurations(result.configurations);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const openModal = (config = null) => {
        if (config) {
            setEditingConfig(config);
            setFormName(config.name);
            setFormDescription(config.description || '');
            setFormActive(config.is_active == 1);
            setFormSigConnectEnabled(config.sig_connect_enabled == 1);
        } else {
            setEditingConfig(null);
            setFormName('');
            setFormDescription('');
            setFormActive(true);
            setFormSigConnectEnabled(false);
        }
        setIsModalOpen(true);
    };

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

        const data = {
            customer_id: customer.id,
            name: formName,
            description: formDescription,
            is_active: formActive ? 1 : 0,
            sig_connect_enabled: formSigConnectEnabled ? 1 : 0
        };

        try {
            if (editingConfig) {
                data.configuration_id = editingConfig.id;
                const result = await api.updateConfiguration(data);
                if (result.success) {
                    toast.success('Configuration modifiée');
                    loadConfigurations();
                    setIsModalOpen(false);
                }
            } else {
                const result = await api.createConfiguration(data);
                if (result.success) {
                    toast.success('Configuration créée');
                    loadConfigurations();
                    setIsModalOpen(false);
                }
            }
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const handleDelete = async (configId) => {
        if (!confirm('Supprimer cette configuration ? Cette action est irréversible.')) return;

        try {
            const result = await api.deleteConfiguration(configId);
            if (result.success) {
                toast.success('Configuration supprimée');
                loadConfigurations();
            }
        } catch (error) {
            toast.error(error.message || 'Erreur lors de la suppression');
        }
    };

    const handleDuplicate = async (config) => {
        const newName = prompt('Nom de la nouvelle configuration:', config.name + ' (Copie)');
        if (!newName) return;

        try {
            const result = await api.duplicateConfiguration(config.id, newName);
            if (result.success) {
                toast.success('Configuration dupliquée');
                loadConfigurations();
            }
        } catch (error) {
            toast.error('Erreur lors de la duplication');
        }
    };

    if (loading) return <Loader />;

    return (
        <div id="sm-configurations-view" className="sm-configurations-view fade-in">
            <div className="flex items-center justify-between mb-8">
                <div>
                    <h1 id="sm-configurations-title" className="text-3xl font-bold text-gray-800">Configurations</h1>
                    <p className="text-gray-600 mt-2">Gérez vos configurations de contenu réutilisables</p>
                </div>
                <Button id="sm-btn-new-config" onClick={() => openModal()} icon="fa-plus">
                    Nouvelle configuration
                </Button>
            </div>

            {configurations.length === 0 ? (
                <Card>
                    <EmptyState
                        icon="fa-cog"
                        title="Aucune configuration"
                        message="Créez votre première configuration de contenu"
                        action={
                            <Button onClick={() => openModal()} icon="fa-plus">
                                Créer une configuration
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div id="sm-configurations-list" className="sm-configurations-list bg-white rounded-lg border border-gray-200 overflow-hidden">
                    {/* En-tête du tableau */}
                    <div className="bg-gray-50 border-b border-gray-200 px-6 py-3 grid grid-cols-12 gap-4 items-center font-semibold text-gray-700 text-sm">
                        <div className="col-span-3">Configuration</div>
                        <div className="col-span-2">Description</div>
                        <div className="col-span-3">Contenu</div>
                        <div className="col-span-1">Écrans</div>
                        <div className="col-span-1">Statut</div>
                        <div className="col-span-2 text-right">Actions</div>
                    </div>
                    
                    {/* Lignes du tableau */}
                    {configurations.map(config => (
                        <div 
                            key={config.id}
                            id={`sm-config-row-${config.id}`}
                            className="border-b border-gray-100 px-6 py-4 grid grid-cols-12 gap-4 items-center hover:bg-gray-50 transition-all"
                        >
                            {/* Nom de la configuration */}
                            <div className="col-span-3 flex items-center gap-3">
                                <div className="w-10 h-10 bg-gradient-to-br from-orange-500 to-red-600 rounded-lg flex items-center justify-center text-white flex-shrink-0">
                                    <i className="fas fa-cog"></i>
                                </div>
                                <div className="min-w-0">
                                    <h3 className="font-semibold text-gray-800 truncate">{config.name}</h3>
                                    <p className="text-xs text-gray-500 truncate">
                                        {new Date(config.created_at).toLocaleDateString('fr-FR')}
                                    </p>
                                </div>
                            </div>

                            {/* Description */}
                            <div className="col-span-2 text-sm text-gray-600">
                                {config.description ? (
                                    <span className="line-clamp-2">{config.description}</span>
                                ) : (
                                    <span className="text-gray-400 italic">Aucune description</span>
                                )}
                            </div>

                            {/* Contenu (statistiques) */}
                            <div className="col-span-3 flex items-center gap-1.5 text-xs flex-wrap">
                                <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded whitespace-nowrap">
                                    <i className="fas fa-image mr-1"></i>{config.ads_count || 0}
                                </span>
                                <span className="px-2 py-1 bg-red-100 text-red-700 rounded whitespace-nowrap">
                                    <i className="fas fa-bell mr-1"></i>{config.news_count || 0}
                                </span>
                                <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded whitespace-nowrap">
                                    <i className="fas fa-align-left mr-1"></i>{config.sliders_count || 0}
                                </span>
                                <span className="px-2 py-1 bg-green-100 text-green-700 rounded whitespace-nowrap">
                                    <i className="fas fa-phone mr-1"></i>{config.numbers_count || 0}
                                </span>
                            </div>

                            {/* Nombre d'écrans */}
                            <div className="col-span-1 text-sm">
                                <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs whitespace-nowrap">
                                    <i className="fas fa-tv mr-1"></i>{config.screens_count || 0}
                                </span>
                            </div>

                            {/* Statut */}
                            <div className="col-span-1">
                                <span className={config.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                    {config.is_active == 1 ? 'Active' : 'Inactive'}
                                </span>
                            </div>

                            {/* Actions */}
                            <div className="col-span-2 flex items-center justify-end gap-2">
                                <button
                                    onClick={() => openModal(config)}
                                    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={() => handleDuplicate(config)}
                                    className="px-3 py-1.5 bg-gray-500 text-white text-sm rounded hover:bg-gray-600 transition-all"
                                    title="Dupliquer"
                                >
                                    <i className="fas fa-copy"></i>
                                </button>
                                <button
                                    onClick={() => handleDelete(config.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>
                        </div>
                    ))}
                </div>
            )}

            {/* Modal Créer/Modifier */}
            <Modal
                id="sm-config-modal"
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingConfig ? 'Modifier la configuration' : 'Nouvelle configuration'}
            >
                <form id="sm-config-form" onSubmit={handleSubmit}>
                    <Input
                        label="Nom de la configuration"
                        value={formName}
                        onChange={setFormName}
                        placeholder="Ex: Configuration Hiver 2024"
                        required
                        icon="fa-cog"
                    />

                    <div className="mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            Description
                        </label>
                        <textarea
                            value={formDescription}
                            onChange={(e) => setFormDescription(e.target.value)}
                            placeholder="Description de la configuration..."
                            rows="3"
                            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                        />
                    </div>

                    <div className="mb-4">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={formActive}
                                onChange={(e) => setFormActive(e.target.checked)}
                                className="w-5 h-5 text-orange-500"
                            />
                            <span className="text-gray-700 font-medium">Configuration active</span>
                        </label>
                    </div>

                    <div className="mb-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div className="mb-3">
                            <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
                                <i className="fas fa-plug text-orange-500"></i>
                                Applications tierces
                            </h3>
                            <p className="text-xs text-gray-500 mt-1">
                                Activez les applications externes pour cette configuration
                            </p>
                        </div>
                        
                        <div className="space-y-3">
                            <label className="flex items-center gap-3 p-3 bg-white rounded-lg border border-gray-200 hover:border-orange-300 cursor-pointer transition-colors">
                                <input
                                    type="checkbox"
                                    checked={formSigConnectEnabled}
                                    onChange={(e) => setFormSigConnectEnabled(e.target.checked)}
                                    className="w-5 h-5 text-orange-500"
                                />
                                <div className="flex-1">
                                    <div className="font-medium text-gray-800">SIG Connect</div>
                                    <div className="text-xs text-gray-500">Affichage en temps réel des données SIG Genève</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div className="p-4 bg-blue-50 rounded-lg mb-4">
                        <div className="flex gap-2 text-sm text-blue-800">
                            <i className="fas fa-info-circle mt-1"></i>
                            <div>
                                Après avoir créé la configuration, vous pourrez y ajouter du contenu 
                                (publicités, alertes, messages, contacts) et l'appliquer à vos écrans.
                            </div>
                        </div>
                    </div>

                    <div className="flex gap-3">
                        <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)} className="flex-1">
                            Annuler
                        </Button>
                        <Button variant="primary" className="flex-1">
                            {editingConfig ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

// ============================================================================
// VUE CARTE
// ============================================================================

const MapView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [screens, setScreens] = useState([]);
    const [loading, setLoading] = useState(true);
    const [centerLat, setCenterLat] = useState(46.2044); // Centre Suisse par défaut
    const [centerLng, setCenterLng] = useState(6.1432);
    const mapRef = useRef(null);
    const markersRef = useRef([]);

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

    useEffect(() => {
        if (!loading && screens.length > 0) {
            initMap();
        }
    }, [loading, screens]);

    const loadScreens = async () => {
        setLoading(true);
        try {
            const result = await api.getScreens(customer.id);
            if (result.screens) {
                setScreens(result.screens);
                
                // Centrer sur l'adresse du client si disponible
                if (customer.latitude && customer.longitude) {
                    setCenterLat(parseFloat(customer.latitude));
                    setCenterLng(parseFloat(customer.longitude));
                } else if (result.screens.length > 0 && result.screens[0].latitude) {
                    // Sinon centrer sur le premier écran
                    setCenterLat(parseFloat(result.screens[0].latitude));
                    setCenterLng(parseFloat(result.screens[0].longitude));
                }
            }
        } catch (error) {
            toast.error('Erreur lors du chargement des écrans');
        }
        setLoading(false);
    };

    const initMap = () => {
        // Charger Leaflet si pas encore chargé
        if (!window.L) {
            // Charger le CSS de Leaflet
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
            document.head.appendChild(link);

            // Charger le JS de Leaflet
            const script = document.createElement('script');
            script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
            script.async = true;
            script.onload = () => {
                setTimeout(createMap, 100); // Petit délai pour s'assurer que Leaflet est prêt
            };
            document.head.appendChild(script);
        } else {
            createMap();
        }
    };

    const createMap = () => {
        // Si la carte existe déjà, la supprimer
        if (mapRef.current) {
            mapRef.current.remove();
            markersRef.current = [];
        }

        // Créer la carte avec OpenStreetMap
        const map = L.map('map-container').setView([centerLat, centerLng], 12);

        // Ajouter la couche OpenStreetMap
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: 19
        }).addTo(map);

        mapRef.current = map;

        // Créer une icône personnalisée pour les marqueurs
        const createCustomIcon = (isActive) => {
            const color = isActive ? '#10b981' : '#ef4444';
            const svgIcon = `
                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="42" viewBox="0 0 32 42">
                    <path d="M16 0C7.163 0 0 7.163 0 16c0 11 16 26 16 26s16-15 16-26C32 7.163 24.837 0 16 0z" 
                          fill="${color}" stroke="white" stroke-width="2"/>
                    <circle cx="16" cy="16" r="8" fill="white"/>
                    <text x="16" y="21" font-size="12" text-anchor="middle" fill="${color}">📺</text>
                </svg>
            `;
            
            return L.divIcon({
                html: svgIcon,
                className: 'custom-marker',
                iconSize: [32, 42],
                iconAnchor: [16, 42],
                popupAnchor: [0, -42]
            });
        };

        const bounds = [];

        // Ajouter un marqueur pour chaque écran
        screens.forEach(screen => {
            if (screen.latitude && screen.longitude) {
                const lat = parseFloat(screen.latitude);
                const lng = parseFloat(screen.longitude);
                
                const marker = L.marker([lat, lng], {
                    icon: createCustomIcon(screen.is_active == 1)
                }).addTo(map);

                // Créer le contenu du popup
                const popupContent = `
                    <div style="padding: 8px; min-width: 200px;">
                        <h3 style="font-weight: bold; margin-bottom: 8px; font-size: 16px;">${screen.label}</h3>
                        <p style="margin: 4px 0; font-size: 14px;"><strong>Ville:</strong> ${screen.location_city}</p>
                        <p style="margin: 4px 0; font-size: 14px;"><strong>Adresse:</strong> ${screen.address}</p>
                        <p style="margin: 4px 0; font-size: 14px;"><strong>Statut:</strong> 
                            <span style="color: ${screen.is_active == 1 ? '#10b981' : '#ef4444'}; font-weight: bold;">
                                ${screen.is_active == 1 ? 'Actif ✓' : 'Inactif ✗'}
                            </span>
                        </p>
                        ${screen.bus_stop_name ? `<p style="margin: 4px 0; font-size: 14px;"><strong>Arrêt:</strong> ${screen.bus_stop_name}</p>` : ''}
                    </div>
                `;

                marker.bindPopup(popupContent);

                markersRef.current.push(marker);
                bounds.push([lat, lng]);
            }
        });

        // Ajuster la vue pour afficher tous les marqueurs
        if (bounds.length > 0) {
            map.fitBounds(bounds, { padding: [50, 50] });
        }
    };

    if (loading) return <Loader />;

    return (
        <div id="sm-map-view" className="sm-map-view fade-in relative" style={{ height: 'calc(100vh - 80px)' }}>
            {/* Contrôles par-dessus la carte */}
            <div className="absolute top-4 left-4 right-4 z-10 flex items-center justify-between">
                <div className="flex items-center gap-3 bg-white px-4 py-3 rounded-lg shadow-lg border border-gray-200">
                    <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full bg-green-500"></div>
                        <span className="text-sm font-medium text-gray-700">Actif ({screens.filter(s => s.is_active == 1).length})</span>
                    </div>
                    <div className="h-4 w-px bg-gray-300"></div>
                    <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full bg-red-500"></div>
                        <span className="text-sm font-medium text-gray-700">Inactif ({screens.filter(s => s.is_active == 0).length})</span>
                    </div>
                </div>
                <Button onClick={loadScreens} icon="fa-sync" className="shadow-lg">
                    Actualiser
                </Button>
            </div>

            {/* Carte en plein écran */}
            <div 
                id="map-container" 
                style={{ width: '100%', height: '100%' }}
                className="bg-gray-100"
            >
                {screens.length === 0 && (
                    <div className="flex items-center justify-center h-full">
                        <EmptyState
                            icon="fa-map"
                            title="Aucun écran à afficher"
                            message="Créez votre premier écran pour le voir sur la carte"
                        />
                    </div>
                )}
            </div>
        </div>
    );
};

