// ============================================================================
// VUE PARAMÈTRES
// ============================================================================
// Note: Le composant AddressAutocomplete est importé depuis components.jsx

const SettingsView = () => {
    const { customer, logout } = useAuth();
    const toast = useToast();
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);

    // Form state
    const [formCompanyName, setFormCompanyName] = useState('');
    const [formContactName, setFormContactName] = useState('');
    const [formEmail, setFormEmail] = useState('');
    const [formPhone, setFormPhone] = useState('');
    const [formAddress, setFormAddress] = useState('');
    const [formLatitude, setFormLatitude] = useState(null);
    const [formLongitude, setFormLongitude] = useState(null);
    const [formLogoUrl, setFormLogoUrl] = useState('');
    const [formAgencyLogoUrl, setFormAgencyLogoUrl] = useState('');
    const [uploadingLogo, setUploadingLogo] = useState(false);
    const [uploadingAgencyLogo, setUploadingAgencyLogo] = useState(false);

    // État pour le changement de mot de passe
    const [showPasswordForm, setShowPasswordForm] = useState(false);
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');

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

    const loadCustomerData = async () => {
        setLoading(true);
        try {
            console.log('📥 Chargement des données client:', customer.id);
            const result = await api.getCustomer(customer.id);
            console.log('📦 Données reçues:', result);
            
            if (result && result.success && result.customer) {
                const customerData = result.customer;
                console.log('✅ Remplissage des champs avec:', customerData);
                
                setFormCompanyName(customerData.company_name || '');
                setFormContactName(customerData.contact_name || '');
                setFormEmail(customerData.email || '');
                setFormPhone(customerData.phone || '');
                setFormAddress(customerData.address || '');
                setFormLatitude(customerData.latitude);
                setFormLongitude(customerData.longitude);
                setFormLogoUrl(customerData.logo_url || '');
                setFormAgencyLogoUrl(customerData.agency_logo_url || '');
                
                console.log('✅ Champs remplis avec succès');
            } else {
                console.warn('⚠️ Aucune donnée client trouvée');
                toast.info('Aucune information client enregistrée');
            }
        } catch (error) {
            console.error('❌ Erreur chargement données:', error);
            toast.error('Erreur lors du chargement des données');
        }
        setLoading(false);
    };

    const handleLogoUpload = 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;
        }

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

    const handleAgencyLogoUpload = 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;
        }

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

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

        try {
            const result = await api.updateCustomer({
                customer_id: customer.id,
                company_name: formCompanyName,
                contact_name: formContactName,
                email: formEmail,
                phone: formPhone,
                address: formAddress,
                latitude: formLatitude,
                longitude: formLongitude,
                logo_url: formLogoUrl,
                agency_logo_url: formAgencyLogoUrl
            });

            if (result.success) {
                toast.success('Informations mises à jour avec succès');
            }
        } catch (error) {
            console.error('Erreur lors de la mise à jour:', error);
            toast.error('Erreur lors de la mise à jour');
        }
        setSaving(false);
    };

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

        if (newPassword !== confirmPassword) {
            toast.error('Les mots de passe ne correspondent pas');
            return;
        }

        if (newPassword.length < 8) {
            toast.error('Le mot de passe doit contenir au moins 8 caractères');
            return;
        }

        try {
            const result = await api.changePassword(customer.id, oldPassword, newPassword);

            if (result.success) {
                toast.success('Mot de passe modifié avec succès');
                setShowPasswordForm(false);
                setOldPassword('');
                setNewPassword('');
                setConfirmPassword('');
            } else {
                toast.error(result.message || 'Erreur lors du changement de mot de passe');
            }
        } catch (error) {
            console.error('Erreur changement mot de passe:', error);
            toast.error('Erreur lors du changement de mot de passe');
        }
    };

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

    return (
        <div id="sm-settings-view" className="sm-settings-view space-y-6">
            <h1 id="sm-settings-title" className="sm-page-title text-3xl font-bold text-gray-800">
                <i className="fas fa-cog mr-3 text-gray-600"></i>
                Paramètres
            </h1>

            {/* Grille 2 colonnes : Informations + Sécurité */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Informations entreprise */}
                <Card id="sm-settings-company-card" className="sm-settings-company-card">
                <h2 className="text-xl font-bold text-gray-800 mb-6">
                    <i className="fas fa-building mr-2 text-blue-500"></i>
                    Informations de l'entreprise
                </h2>

                <form id="sm-settings-form" className="sm-settings-form" onSubmit={handleSubmit}>
                    {/* Upload du logo */}
                    <div id="sm-settings-logo-group" className="sm-form-group mb-6">
                        <label className="block text-gray-700 font-medium mb-2">
                            <i className="fas fa-image mr-2"></i>
                            Logo de l'entreprise
                        </label>
                        
                        <div className="flex items-start gap-4">
                            {/* Preview du logo */}
                            <div className="flex-shrink-0">
                                {formLogoUrl ? (
                                    <div className="relative group">
                                        <img 
                                            src={formLogoUrl} 
                                            alt="Logo" 
                                            className="w-32 h-32 object-contain border-2 border-gray-200 rounded-lg"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setFormLogoUrl('')}
                                            className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                        >
                                            <i className="fas fa-times text-xs"></i>
                                        </button>
                                    </div>
                                ) : (
                                    <div className="w-32 h-32 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center bg-gray-50">
                                        <i className="fas fa-image text-4xl text-gray-300"></i>
                                    </div>
                                )}
                            </div>

                            {/* Upload zone */}
                            <div className="flex-1">
                                <div 
                                    className="upload-zone p-6 text-center cursor-pointer"
                                    onClick={() => document.getElementById('logo-file-input').click()}
                                >
                                    {uploadingLogo ? (
                                        <div>
                                            <i className="fas fa-spinner fa-spin text-3xl text-orange-500 mb-2"></i>
                                            <p className="text-sm text-gray-600">Upload en cours...</p>
                                        </div>
                                    ) : (
                                        <div>
                                            <i className="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                            <p className="text-gray-600">
                                                {formLogoUrl ? 'Cliquez pour changer le logo' : 'Cliquez pour uploader un logo'}
                                            </p>
                                            <p className="text-xs text-gray-400 mt-1">
                                                PNG, JPG (max 2MB)
                                            </p>
                                        </div>
                                    )}
                                </div>
                                <input
                                    id="logo-file-input"
                                    type="file"
                                    accept="image/*"
                                    onChange={handleLogoUpload}
                                    className="hidden"
                                />
                                <p className="text-xs text-gray-500 mt-2">
                                    💡 Ce logo apparaîtra sur vos écrans et documents
                                </p>
                            </div>
                        </div>
                    </div>

                    {/* Upload du logo agence immobilière */}
                    <div id="sm-settings-agency-logo-group" className="sm-form-group mb-6">
                        <label className="sm-form-label block text-sm font-semibold text-gray-700 mb-3">
                            <i className="fas fa-home mr-2"></i>
                            Logo Agence Immobilière (optionnel)
                        </label>
                        
                        <div className="flex items-start gap-4">
                            {/* Preview du logo agence */}
                            <div className="flex-shrink-0">
                                {formAgencyLogoUrl ? (
                                    <div className="relative group">
                                        <img 
                                            src={formAgencyLogoUrl} 
                                            alt="Logo Agence" 
                                            className="w-32 h-32 object-contain border-2 border-gray-200 rounded-lg"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setFormAgencyLogoUrl('')}
                                            className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                        >
                                            <i className="fas fa-times text-xs"></i>
                                        </button>
                                    </div>
                                ) : (
                                    <div className="w-32 h-32 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center bg-gray-50">
                                        <i className="fas fa-home text-4xl text-gray-300"></i>
                                    </div>
                                )}
                            </div>

                            {/* Upload zone */}
                            <div className="flex-1">
                                <div 
                                    className="upload-zone p-6 text-center cursor-pointer"
                                    onClick={() => document.getElementById('agency-logo-file-input').click()}
                                >
                                    {uploadingAgencyLogo ? (
                                        <div>
                                            <i className="fas fa-spinner fa-spin text-3xl text-orange-500 mb-2"></i>
                                            <p className="text-sm text-gray-600">Upload en cours...</p>
                                        </div>
                                    ) : (
                                        <div>
                                            <i className="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                            <p className="text-gray-600">
                                                {formAgencyLogoUrl ? 'Cliquez pour changer le logo' : 'Cliquez pour uploader un logo'}
                                            </p>
                                            <p className="text-xs text-gray-400 mt-1">
                                                PNG, JPG (max 2MB)
                                            </p>
                                        </div>
                                    )}
                                </div>
                                <input
                                    id="agency-logo-file-input"
                                    type="file"
                                    accept="image/*"
                                    onChange={handleAgencyLogoUpload}
                                    className="hidden"
                                />
                                <p className="text-xs text-gray-500 mt-2">
                                    🏠 Ce logo apparaîtra uniquement sur les annonces immobilières
                                </p>
                            </div>
                        </div>
                    </div>

                    <Input
                        id="sm-settings-company-name"
                        label="Nom de l'entreprise"
                        value={formCompanyName}
                        onChange={setFormCompanyName}
                        required
                        icon="fa-building"
                    />

                    <Input
                        id="sm-settings-contact-name"
                        label="Nom du contact"
                        value={formContactName}
                        onChange={setFormContactName}
                        required
                        icon="fa-user"
                    />

                    <Input
                        id="sm-settings-phone"
                        label="Téléphone"
                        type="tel"
                        value={formPhone}
                        onChange={setFormPhone}
                        icon="fa-phone"
                    />

                    <AddressAutocomplete
                        id="sm-settings-address"
                        label="Adresse complète"
                        value={formAddress}
                        onAddressSelected={(data) => {
                            setFormAddress(data.address);
                            setFormLatitude(data.latitude);
                            setFormLongitude(data.longitude);
                        }}
                        placeholder="Commencez à taper votre adresse..."
                        required
                    />

                    {formLatitude && formLongitude && (
                        <div className="mb-4 p-3 bg-green-50 rounded-lg text-sm">
                            <i className="fas fa-map-marker-alt text-green-600 mr-2"></i>
                            Coordonnées GPS: {parseFloat(formLatitude).toFixed(6)}, {parseFloat(formLongitude).toFixed(6)}
                        </div>
                    )}

                    <Button
                        id="sm-settings-save-btn"
                        type="submit"
                        variant="primary"
                        className="w-full"
                        disabled={saving}
                    >
                        {saving ? 'Enregistrement...' : 'Enregistrer les modifications'}
                    </Button>
                </form>
                </Card>

                {/* Sécurité */}
                <Card id="sm-settings-security-card" className="sm-settings-security-card">
                <h2 className="text-xl font-bold text-gray-800 mb-6">
                    <i className="fas fa-shield-alt mr-2 text-orange-500"></i>
                    Sécurité
                </h2>

                <div className="mb-6">
                    <Input
                        id="sm-settings-email"
                        label="Email"
                        type="email"
                        value={formEmail}
                        onChange={setFormEmail}
                        required
                        icon="fa-envelope"
                    />
                </div>

                {!showPasswordForm ? (
                    <div className="space-y-4">
                        <div className="p-4 bg-gray-50 rounded-lg">
                            <div className="flex items-center justify-between">
                                <div>
                                    <div className="font-semibold text-gray-800">Mot de passe</div>
                                    <div className="text-sm text-gray-600">••••••••</div>
                                </div>
                                <Button
                                    variant="secondary"
                                    onClick={() => setShowPasswordForm(true)}
                                >
                                    Modifier
                                </Button>
                            </div>
                        </div>

                        <div className="p-4 bg-gray-50 rounded-lg">
                            <div className="flex items-center justify-between">
                                <div>
                                    <div className="font-semibold text-gray-800">Déconnexion</div>
                                    <div className="text-sm text-gray-600">Se déconnecter de l'application</div>
                                </div>
                                <Button
                                    variant="danger"
                                    onClick={logout}
                                >
                                    <i className="fas fa-sign-out-alt mr-2"></i>
                                    Déconnexion
                                </Button>
                            </div>
                        </div>
                    </div>
                ) : (
                    <form onSubmit={handlePasswordChange} className="space-y-4">
                        <Input
                            label="Ancien mot de passe"
                            type="password"
                            value={oldPassword}
                            onChange={setOldPassword}
                            required
                            icon="fa-lock"
                        />

                        <Input
                            label="Nouveau mot de passe"
                            type="password"
                            value={newPassword}
                            onChange={setNewPassword}
                            required
                            icon="fa-key"
                        />

                        <Input
                            label="Confirmer le nouveau mot de passe"
                            type="password"
                            value={confirmPassword}
                            onChange={setConfirmPassword}
                            required
                            icon="fa-key"
                        />

                        <div className="flex gap-3">
                            <Button
                                type="button"
                                variant="secondary"
                                onClick={() => {
                                    setShowPasswordForm(false);
                                    setOldPassword('');
                                    setNewPassword('');
                                    setConfirmPassword('');
                                }}
                                className="flex-1"
                            >
                                Annuler
                            </Button>
                            <Button
                                type="submit"
                                variant="primary"
                                className="flex-1"
                            >
                                Changer le mot de passe
                            </Button>
                        </div>
                    </form>
                )}
                </Card>
            </div>
        </div>
    );
};
