@extends('layouts.admin')

@section('title', 'Configuration des Fonctionnalités')

@section('content')
<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-1"><i class="bi bi-sliders me-2"></i>Configuration Avancée des Fonctionnalités</h1>
                    <p class="text-muted mb-0">Paramétrez toutes les capacités de votre plateforme</p>
                </div>
                <a href="{{ route('admin.features.index') }}" class="btn btn-secondary">
                    <i class="bi bi-arrow-left me-2"></i>Retour
                </a>
            </div>
        </div>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show">
            <i class="bi bi-check-circle me-2"></i>{{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="bi bi-exclamation-circle me-2"></i>{{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <!-- Filtrage par catégorie -->
    <div class="card mb-4">
        <div class="card-body">
            <h6 class="mb-3">Filtrer par catégorie</h6>
            <div class="btn-group flex-wrap" role="group">
                <button type="button" class="btn btn-outline-primary category-filter active" data-category="all">
                    <i class="bi bi-funnel me-1"></i>Toutes
                </button>
                @foreach($categories as $categoryKey => $categoryName)
                    @if($features->where('category', $categoryKey)->count() > 0)
                        <button type="button" class="btn btn-outline-primary category-filter" data-category="{{ $categoryKey }}">
                            {{ $categoryName }} ({{ $features->where('category', $categoryKey)->count() }})
                        </button>
                    @endif
                @endforeach
            </div>
        </div>
    </div>

    <!-- Statistiques par catégorie -->
    <div class="row g-3 mb-4">
        @foreach($categories as $categoryKey => $categoryName)
            @php
                $categoryFeatures = $features->where('category', $categoryKey);
                if($categoryFeatures->count() === 0) continue;
                $enabledCount = $categoryFeatures->where('is_enabled', true)->count();
                $totalCount = $categoryFeatures->count();
                $percent = $totalCount > 0 ? round(($enabledCount / $totalCount) * 100) : 0;
            @endphp
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h6 class="mb-0">{{ $categoryName }}</h6>
                            <span class="badge bg-primary">{{ $percent }}%</span>
                        </div>
                        <p class="text-muted small mb-2">{{ $enabledCount }} / {{ $totalCount }} activées</p>
                        <div class="progress" style="height: 6px;">
                            <div class="progress-bar" role="progressbar" style="width: {{ $percent }}%"></div>
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    <!-- Configuration par catégorie -->
    <div class="accordion" id="configAccordion">
        @foreach($categories as $categoryKey => $categoryName)
            @php
                $categoryFeatures = $features->where('category', $categoryKey);
                if($categoryFeatures->count() === 0) continue;
            @endphp
            
            <div class="accordion-item" data-category="{{ $categoryKey }}">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#category-{{ $categoryKey }}">
                        <i class="bi bi-folder me-2"></i>{{ $categoryName }}
                        <span class="badge bg-secondary ms-2">{{ $categoryFeatures->count() }}</span>
                        <span class="badge bg-success ms-1">{{ $categoryFeatures->where('is_enabled', true)->count() }} activées</span>
                    </button>
                </h2>
                <div id="category-{{ $categoryKey }}" class="accordion-collapse collapse" data-bs-parent="#configAccordion">
                    <div class="accordion-body">
                        <div class="row g-4">
                            @foreach($categoryFeatures as $feature)
                                <div class="col-lg-6">
                                    <div class="card border-light h-100">
                                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1">{{ $feature->name }}</h6>
                                                <small class="text-muted">{{ $feature->feature_key }}</small>
                                            </div>
                                            @if($feature->is_enabled)
                                                <span class="badge bg-success">ON</span>
                                            @else
                                                <span class="badge bg-secondary">OFF</span>
                                            @endif
                                        </div>
                                        <div class="card-body">
                                            <p class="card-text small text-muted mb-3">{{ $feature->description }}</p>

                                            <!-- Toggle ON/OFF -->
                                            <form action="{{ route('admin.features.toggle', $feature->feature_key) }}" method="POST" class="mb-3 d-inline-block">
                                                @csrf
                                                <button type="submit" class="btn btn-sm {{ $feature->is_enabled ? 'btn-warning' : 'btn-success' }}">
                                                    @if($feature->is_enabled)
                                                        <i class="bi bi-toggle-off me-1"></i>Désactiver
                                                    @else
                                                        <i class="bi bi-toggle-on me-1"></i>Activer
                                                    @endif
                                                </button>
                                            </form>

                                            <!-- Configuration si existe -->
                                            @if($feature->config && is_array($feature->config) && count($feature->config) > 0)
                                                <hr class="my-3">
                                                <h6 class="mb-3">
                                                    <i class="bi bi-gear me-1"></i>Paramètres
                                                </h6>
                                                <form action="{{ route('admin.features.config', $feature->feature_key) }}" method="POST" class="needs-validation">
                                                    @csrf
                                                    @method('PUT')

                                                    @foreach($feature->config as $key => $value)
                                                        @php
                                                            $label = ucfirst(str_replace('_', ' ', $key));
                                                            $inputName = "config[{$key}]";
                                                            $inputId = "config-{$feature->feature_key}-{$key}";
                                                        @endphp

                                                        <div class="mb-2">
                                                            <label for="{{ $inputId }}" class="form-label small fw-bold">{{ $label }}</label>
                                                            
                                                            @if(is_bool($value))
                                                                <!-- Toggle pour booléens -->
                                                                <div class="form-check form-switch">
                                                                    <input class="form-check-input" type="checkbox" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           {{ $value ? 'checked' : '' }}>
                                                                    <label class="form-check-label small" for="{{ $inputId }}">
                                                                        {{ $value ? 'Activé' : 'Désactivé' }}
                                                                    </label>
                                                                </div>
                                                            @elseif(is_numeric($value))
                                                                @if(strpos($key, 'temperature') !== false || strpos($key, 'confidence') !== false)
                                                                    <!-- Slider pour les scores 0-1 -->
                                                                    <input type="range" class="form-range config-slider" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           value="{{ $value }}"
                                                                           min="0" max="1" step="0.1"
                                                                           data-display="{{ $inputId }}-display">
                                                                    <small class="text-muted">Valeur: <span id="{{ $inputId }}-display">{{ $value }}</span></small>
                                                                @elseif(strpos($key, 'percent') !== false)
                                                                    <!-- Slider pour les pourcentages -->
                                                                    <input type="range" class="form-range config-slider" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           value="{{ $value }}"
                                                                           min="0" max="100" step="5"
                                                                           data-display="{{ $inputId }}-display">
                                                                    <small class="text-muted">Valeur: <span id="{{ $inputId }}-display">{{ $value }}%</span></small>
                                                                @else
                                                                    <!-- Input normal pour les nombres -->
                                                                    <input type="number" class="form-control form-control-sm" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           value="{{ $value }}"
                                                                           min="0">
                                                                @endif
                                                            @elseif(is_array($value))
                                                                <!-- Textarea pour les tableaux/objets -->
                                                                <textarea class="form-control form-control-sm font-monospace" 
                                                                          id="{{ $inputId }}" 
                                                                          name="{{ $inputName }}"
                                                                          rows="2"
                                                                          style="font-size: 11px;">{{ json_encode($value, JSON_PRETTY_PRINT) }}</textarea>
                                                                <small class="text-muted d-block">Format JSON</small>
                                                            @else
                                                                <!-- Texte pour les chaînes -->
                                                                @if(strpos($key, 'password') !== false || strpos($key, 'token') !== false || strpos($key, 'api_key') !== false || strpos($key, 'secret') !== false)
                                                                    <input type="password" class="form-control form-control-sm" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           value="{{ $value }}"
                                                                           placeholder="Clé sécurisée">
                                                                @elseif(in_array($value, ['low', 'medium', 'high', 'professional', 'casual', 'formal', 'openai', 'claude', 'gpt-4', 'gpt-3.5', 'fr', 'en', 'es']) || strpos($key, 'language') !== false || strpos($key, 'model') !== false || strpos($key, 'tone') !== false || strpos($key, 'sensitivity') !== false)
                                                                    <!-- Sélection intelligente -->
                                                                    <select class="form-select form-select-sm" id="{{ $inputId }}" name="{{ $inputName }}">
                                                                        @if(strpos($key, 'sensitivity') !== false)
                                                                            <option value="low" {{ $value === 'low' ? 'selected' : '' }}>Bas</option>
                                                                            <option value="medium" {{ $value === 'medium' ? 'selected' : '' }}>Moyen</option>
                                                                            <option value="high" {{ $value === 'high' ? 'selected' : '' }}>Élevé</option>
                                                                        @elseif(strpos($key, 'tone') !== false)
                                                                            <option value="professional" {{ $value === 'professional' ? 'selected' : '' }}>Professionnel</option>
                                                                            <option value="casual" {{ $value === 'casual' ? 'selected' : '' }}>Décontracté</option>
                                                                            <option value="formal" {{ $value === 'formal' ? 'selected' : '' }}>Formel</option>
                                                                        @elseif(strpos($key, 'model') !== false)
                                                                            <option value="gpt-4" {{ $value === 'gpt-4' ? 'selected' : '' }}>GPT-4</option>
                                                                            <option value="gpt-3.5" {{ $value === 'gpt-3.5' ? 'selected' : '' }}>GPT-3.5</option>
                                                                            <option value="claude" {{ $value === 'claude' ? 'selected' : '' }}>Claude</option>
                                                                        @elseif(strpos($key, 'api_provider') !== false)
                                                                            <option value="openai" {{ $value === 'openai' ? 'selected' : '' }}>OpenAI</option>
                                                                            <option value="claude" {{ $value === 'claude' ? 'selected' : '' }}>Anthropic (Claude)</option>
                                                                        @elseif(strpos($key, 'language') !== false)
                                                                            <option value="fr" {{ $value === 'fr' ? 'selected' : '' }}>Français</option>
                                                                            <option value="en" {{ $value === 'en' ? 'selected' : '' }}>English</option>
                                                                            <option value="es" {{ $value === 'es' ? 'selected' : '' }}>Español</option>
                                                                        @else
                                                                            <option value="{{ $value }}" selected>{{ $value }}</option>
                                                                        @endif
                                                                    </select>
                                                                @else
                                                                    <input type="text" class="form-control form-control-sm" 
                                                                           id="{{ $inputId }}" 
                                                                           name="{{ $inputName }}"
                                                                           value="{{ $value }}"
                                                                           placeholder="Entrez une valeur">
                                                                @endif
                                                            @endif
                                                        </div>
                                                    @endforeach

                                                    <div class="mt-3">
                                                        <button type="submit" class="btn btn-primary btn-sm">
                                                            <i class="bi bi-check2 me-1"></i>Enregistrer
                                                        </button>
                                                    </div>
                                                </form>
                                            @else
                                                <div class="alert alert-info alert-sm" role="alert">
                                                    <small><i class="bi bi-info-circle me-1"></i>Aucun paramètre pour cette fonctionnalité</small>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</div>

<script>
// Synchroniser les sliders avec leur affichage
document.querySelectorAll('.config-slider').forEach(slider => {
    slider.addEventListener('input', function() {
        const displayId = this.dataset.display;
        const displayElement = document.getElementById(displayId);
        if (displayElement) {
            displayElement.textContent = this.value + (this.max === '100' ? '%' : '');
        }
    });
});

// Filtrage par catégorie
document.querySelectorAll('.category-filter').forEach(button => {
    button.addEventListener('click', function() {
        const category = this.dataset.category;
        
        // Mettre à jour le bouton actif
        document.querySelectorAll('.category-filter').forEach(b => b.classList.remove('active'));
        this.classList.add('active');
        
        // Filtrer les éléments
        document.querySelectorAll('.accordion-item').forEach(item => {
            if (category === 'all' || item.dataset.category === category) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
});

// Validation Bootstrap
(() => {
    'use strict';
    window.addEventListener('load', () => {
        const forms = document.querySelectorAll('.needs-validation');
        Array.from(forms).forEach(form => {
            form.addEventListener('submit', event => {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>

<style>
.category-filter.active {
    background-color: #0d6efd;
    color: white;
}

.alert-sm {
    padding: 0.5rem 0.75rem;
    font-size: 0.875rem;
}

.card {
    transition: all 0.2s ease;
}

.card:hover {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

.accordion-button:not(.collapsed) {
    background-color: #e7f3ff;
    color: #0d6efd;
}

.form-control-sm, .form-select-sm {
    font-size: 0.875rem;
}

.config-slider {
    height: 4px;
}
</style>
@endsection
