{% extends "base.html" %}

{% block title %}Gestión de Tarifas{% endblock %}

{% block content %}
<div id="admin-content" class="container-fluid">
        <div class="row">
            <div class="col-12 mb-4 admin-header">
                <h1>Gestión de Tarifas</h1>
            </div>
        </div>
        <div class="row mb-4">
            <div class="col-md-6">
                <p class="mb-0">Administre las tarifas disponibles para comparar con las facturas de los clientes.</p>
            </div>
            <div class="col-md-6 text-md-end">
                <button id="toggleFiltersBtn" class="btn btn-outline-secondary me-2" type="button"
                        data-bs-toggle="collapse" data-bs-target="#filtersCollapse" aria-expanded="false"
                        aria-controls="filtersCollapse">
                    <i class="fas fa-filter me-1"></i>
                    <span class="toggle-text">Mostrar filtros</span>
                </button>
                <a href="{{ url_for('admin.export_rates_csv', id=filter_id, supplier=filter_supplier, name=filter_name, tariff_type=filter_tariff_type, valid_from=filter_valid_from, valid_until=filter_valid_until) }}" class="btn btn-outline-success me-2">
                    <i class="fas fa-file-csv me-1"></i> Exportar CSV
                </a>
                {% if not is_comercial %}
                <a href="{{ url_for('admin.rates_csv_template') }}" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-download me-1"></i> Plantilla CSV
                </a>
                <button class="btn btn-outline-primary me-2" type="button" data-bs-toggle="modal" data-bs-target="#importCsvModal">
                    <i class="fas fa-file-upload me-1"></i> Importar CSV
                </button>
                {% if not is_comercial %}
                <a href="{{ url_for('admin.create_rate') }}" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i> Nueva Tarifa
                </a>
                {% endif %}
                {% endif %}
            </div>
        </div>
        
        <!-- Filtros y controles avanzados (inspirado en el diseño de leads) -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="collapse" id="filtersCollapse">
                <div class="card shadow-sm filters-card">
                    <div class="card-body py-3">
                        <form method="get" id="filtersForm">
                            <div class="row g-3">
                                <!-- Columna izquierda: ID arriba, Comercializadora abajo -->
                                <div class="col-md-5">
                                    <div class="mb-2">
                                        <label for="filter_id" class="form-label fw-bold small text-muted mb-1">ID</label>
                                        <input type="text" class="form-control" id="filter_id" name="id" placeholder="ID" value="{{ filter_id or '' }}">
                                    </div>
                                    <div>
                                        <label for="filterSupplierSelect" class="form-label fw-bold small text-muted mb-1">Comercializadora</label>
                                        <select id="filterSupplierSelect" name="supplier" class="form-select" data-current-supplier="{{ filter_supplier or '' }}">
                                            <option value="">Todas</option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Columna derecha: Nombre del plan arriba, Tipo de tarifa abajo -->
                                <div class="col-md-5">
                                    <div class="mb-2">
                                        <label for="filterName" class="form-label fw-bold small text-muted mb-1">Nombre del plan</label>
                                        <input type="text" class="form-control" id="filterName" name="name" placeholder="Nombre de tarifa" value="{{ filter_name or '' }}">
                                    </div>
                                    <div>
                                        <label for="filter_tariff_type" class="form-label fw-bold small text-muted mb-1">Tipo de tarifa</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text"><i class="fas fa-bolt"></i></span>
                                            <input type="text" name="tariff_type" id="filter_tariff_type" class="form-control" placeholder="Tipo tarifa" value="{{ filter_tariff_type or '' }}">
                                        </div>
                                    </div>
                                </div>

                                <!-- Rango de fechas: se mantiene como está (Desde / Hasta apilados) -->
                                <div class="col-md-2 col-sm-12">
                                    <div class="row g-2">
                                        <div class="col-sm-6 col-md-12">
                                            <label for="filter_valid_from" class="form-label fw-bold small text-muted mb-1">Desde</label>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                                <input type="date" name="valid_from" id="filter_valid_from" class="form-control" value="{{ filter_valid_from }}">
                                            </div>
                                        </div>
                                        <div class="col-sm-6 col-md-12">
                                            <label for="filter_valid_until" class="form-label fw-bold small text-muted mb-1">Hasta</label>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                                <input type="date" name="valid_until" id="filter_valid_until" class="form-control" value="{{ filter_valid_until }}">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Botones de acción -->
                            <div class="row mt-3">
                                <div class="col-12 d-flex flex-wrap align-items-center justify-content-between">
                                    <div class="d-flex align-items-center mb-2 mb-md-0">
                                        <label for="per_page" class="form-label fw-bold small text-muted mb-0 me-2">Resultados por página</label>
                                        <select name="per_page" id="per_page" class="form-select form-select-sm" style="width: auto;">
                                            <option value="10" {% if per_page == 10 %}selected{% endif %}>10</option>
                                            <option value="25" {% if per_page == 25 %}selected{% endif %}>25</option>
                                            <option value="50" {% if per_page == 50 %}selected{% endif %}>50</option>
                                            <option value="100" {% if per_page == 100 %}selected{% endif %}>100</option>
                                        </select>
                                    </div>
                                    <div class="d-flex">
                                        <a href="{{ url_for('admin.list_rates') }}" class="btn btn-sm btn-outline-secondary me-2">
                                            <i class="fas fa-sync-alt me-1"></i> Limpiar
                                        </a>
                                        <button type="submit" class="btn btn-sm btn-primary">
                                            <i class="fas fa-search me-1"></i> Buscar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                </div>
            </div>
        </div>
        
        <!-- Estadísticas y conteo -->
        <div class="row mb-3">
            <div class="col-12 text-end">
                <span class="text-muted small">Mostrando {{ rates|length }} de {{ pagination.total if pagination else 0 }} tarifas</span>
            </div>
        </div>
        
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body p-0">
                        {% if pagination and pagination.items %}
                            <div class="table-responsive">
                                <table class="table table-hover table-striped table-bordered rates-table align-middle">
                                    <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>Comercializadora</th>
                                        <th>Nombre</th>
                                        <th>Tipo de tarifa</th>
                                        <th class="text-nowrap">Válido Desde</th>
                                        <th class="text-nowrap">Válido Hasta</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for rate in pagination.items %}
                                    <tr>
                                        <td>{{ rate.id }}</td>
                                        <td>{{ rate.supplier or 'No especificada' }}</td>
                                        <td>{{ rate.name }}</td>
                                        <td><span class="badge bg-secondary">{{ rate.tariff_type }}</span></td>
                                        <td class="text-nowrap">{{ rate.valid_from or 'Sin fecha' }}</td>
                                        <td class="text-nowrap">{{ rate.valid_until or 'Sin fecha' }}</td>
                                        <td class="text-nowrap">
                                            <div class="btn-group flex-nowrap">
                                                <button type="button" class="btn btn-sm btn-outline-secondary btn-view" 
                                                        data-rate-id="{{ rate.id }}" title="Ver detalles">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                {% if not is_comercial %}
                                                <a href="{{ url_for('admin.edit_rate', rate_id=rate.id) }}" 
                                                   class="btn btn-sm btn-outline-primary" title="Editar Tarifa">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button type="button" class="btn btn-sm btn-outline-danger" 
                                                         data-rate-id="{{ rate.id }}" 
                                                         data-rate-name="{{ rate.name }}" 
                                                         onclick="confirmDelete(this.getAttribute('data-rate-id'), this.getAttribute('data-rate-name'))" title="Eliminar Tarifa">
                                                     <i class="fas fa-trash-alt"></i>
                                                 </button>
                                                {% endif %}
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                                </table>
                            </div>
                            {% else %}
                            <div class="text-center py-4">
                                <div class="d-flex flex-column align-items-center">
                                    <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No hay tarifas disponibles</h5>
                                    <p class="text-muted">No se encontraron tarifas con los filtros actuales o no hay ninguna registrada. Pruebe a limpiar los filtros o añada una nueva tarifa.</p>
                                    <a href="{{ url_for('admin.create_rate') }}" class="btn btn-primary mt-2">
                                        <i class="fas fa-plus-circle me-2"></i>Añadir primera tarifa
                                    </a>
                                </div>
                            </div>
                            {% endif %}

                            {# Pagination controls #}
                            {% if pagination.total > 0 %}
                            <nav aria-label="Page navigation">
                                <ul class="pagination pagination-sm flex-wrap justify-content-center mt-4">{% if pagination.has_prev %}<li class="page-item">
                                    <a class="page-link" href="{{ url_for('admin.list_rates', page=pagination.prev_num, per_page=per_page, id=filter_id, supplier=filter_supplier, name=filter_name, tariff_type=filter_tariff_type, valid_from=filter_valid_from, valid_until=filter_valid_until) }}" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                {% endif %}
                                {% for p in pagination.iter_pages() %}
                                {% if p %}
                                    {% if p == pagination.page %}
                                    <li class="page-item active" aria-current="page"><a class="page-link" href="#">{{ p }}</a></li>
                                    {% else %}
                                    <li class="page-item"><a class="page-link" href="{{ url_for('admin.list_rates', page=p, per_page=per_page, id=filter_id, supplier=filter_supplier, name=filter_name, tariff_type=filter_tariff_type, valid_from=filter_valid_from, valid_until=filter_valid_until) }}">{{ p }}</a></li>
                                    {% endif %}
                                {% else %}
                                <li class="page-item disabled"><a class="page-link" href="#">...</a></li>
                                {% endif %}
                                {% endfor %}
                                {% if pagination.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('admin.list_rates', page=pagination.next_num, per_page=per_page, id=filter_id, supplier=filter_supplier, name=filter_name, tariff_type=filter_tariff_type, valid_from=filter_valid_from, valid_until=filter_valid_until) }}" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                                {% endif %}
                            </ul>
                        </nav>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
</div>

<!-- Modal de confirmación para eliminar -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">Confirmar eliminación</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>¿Está seguro de que desea eliminar la tarifa <strong id="deleteTariffName"></strong>?</p>
                <p class="text-danger">Esta acción no se puede deshacer.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <form id="deleteForm" method="POST" action="">
                    {% if csrf_form %}{{ csrf_form.csrf_token }}{% endif %}
                    <button type="submit" class="btn btn-danger">Eliminar</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Importar CSV -->
<div class="modal fade" id="importCsvModal" tabindex="-1" aria-labelledby="importCsvModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importCsvModalLabel"><i class="fas fa-file-upload me-2"></i> Importar Tarifas desde CSV</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="{{ url_for('admin.import_rates_csv') }}" enctype="multipart/form-data">
                <div class="modal-body">
                    {% if csrf_form %}{{ csrf_form.csrf_token }}{% endif %}
                    <div class="mb-3">
                        <label for="csvFile" class="form-label">Archivo CSV</label>
                        <input class="form-control" type="file" id="csvFile" name="file" accept=".csv" required>
                        <div class="form-text">
                            Formato esperado de cabeceras: id, supplier, name, tariff_type, valid_from, valid_until, notes,
                            energy_P1..P6, power_P1..P6. Codificación UTF-8 (mejor con BOM para Excel).
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-upload me-1"></i> Importar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal personalizado de detalle de tarifa -->
<div class="custom-modal" id="viewRateModal">
    <!-- Overlay de fondo oscuro -->
    <div class="custom-modal-overlay"></div>
    
    <!-- Contenedor del modal centrado -->
    <div class="custom-modal-container">
        <!-- Contenido del modal -->
        <div class="custom-modal-content rate-detail-modal">
            <!-- Encabezado del modal con título y botón de cierre -->
            <div class="custom-modal-header">
                <div class="d-flex align-items-center">
                    <i class="fas fa-bolt me-2 text-primary"></i>
                    <h5 class="custom-modal-title" id="viewRateLabel">Detalle de Tarifa</h5>
                </div>
                <button type="button" class="custom-modal-close" id="modalCloseButton">&times;</button>
            </div>
            
            <!-- Cuerpo del modal -->
            <div class="custom-modal-body">
                <div id="rateDetailContent">
                    <!-- Información principal en tarjeta -->
                    <div class="info-card mb-3">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-barcode"></i> ID</span>
                                    <span class="detail-value fw-bold fs-5" id="d_id"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-building me-2"></i>Comercializadora</span>
                                    <span class="detail-value" id="d_supplier"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-file-signature"></i> Nombre</span>
                                    <span class="detail-value" id="d_name"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-bolt"></i> Tipo</span>
                                    <span class="detail-value badge bg-primary" id="d_tariff_type"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Fechas y validez -->
                    <div class="date-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-calendar-check me-1"></i> Período de validez</h6>
                        </div>
                        <div class="card-body py-2">
                            <div class="row align-items-center">
                                <div class="col-md-5">
                                    <div class="detail-item">
                                        <span class="detail-label">Desde</span>
                                        <span class="detail-value text-success fw-bold" id="d_valid_from"></span>
                                    </div>
                                </div>
                                <div class="col-md-2 text-center d-none d-md-block">
                                    <i class="fas fa-long-arrow-alt-right fa-2x text-muted"></i>
                                </div>
                                <div class="col-md-5 text-center">
                                    <div class="detail-item">
                                        <span class="detail-label">Hasta</span>
                                        <span class="detail-value text-danger fw-bold" id="d_valid_until"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Notas -->
                    <div class="notes-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-info-circle me-2"></i>Notas</h6>
                        </div>
                        <div class="card-body py-2">
                            <div id="d_notes" class="text-muted fst-italic"></div>
                        </div>
                    </div>
                    
                    <!-- Precios en formato de tarjetas -->
                    <div class="row">
                        <!-- Precios de Energía -->
                        <div class="col-lg-6 mb-3">
                            <div class="prices-card energy-card">
                                <div class="card-header text-white py-2" style="background-color: #0b99fd;">
                                    <h6 class="m-0"><i class="fas fa-lightbulb me-2"></i>Precios de Energía (€/kWh)</h6>
                                </div>
                                <div class="card-body p-0">
                                    <table class="table table-hover table-sm mb-0">
                                        <thead>
                                            <tr class="table-light">
                                                <th class="text-center" style="width:30%">Periodo</th>
                                                <th class="text-end">Precio</th>
                                            </tr>
                                        </thead>
                                        <tbody id="d_energy_prices"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Precios de Potencia -->
                        <div class="col-lg-6 mb-3">
                            <div class="prices-card power-card">
                                <div class="card-header bg-success text-white py-2">
                                    <h6 class="m-0"><i class="fas fa-battery-full me-1"></i> Precios de Potencia (€/kW)</h6>
                                </div>
                                <div class="card-body p-0">
                                    <table class="table table-hover table-sm mb-0">
                                        <thead>
                                            <tr class="table-light">
                                                <th class="text-center" style="width:30%">Periodo</th>
                                                <th class="text-end">Precio</th>
                                            </tr>
                                        </thead>
                                        <tbody id="d_power_prices"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Pie del modal con botones -->
            <div class="custom-modal-footer">
                <button type="button" class="btn btn-secondary" id="modalCloseBtn">
                    <i class="fas fa-times me-1"></i> Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Estilos para el modal personalizado -->
<style>
    /* Estilos base del modal personalizado */
    .custom-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        z-index: 9999;
    }
    
    .custom-modal-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(3px);
    }
    
    .custom-modal-container {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        box-sizing: border-box;
    }
    
    .custom-modal-content {
        background-color: #ffffff;
        width: 100%;
        max-width: 800px;
        border-radius: 10px;
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
        margin: auto;
        animation: modalFadeIn 0.3s ease-out;
        position: relative;
        max-height: 85vh;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    
    .custom-modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-bottom: 1px solid #e9ecef;
        background-color: #f8f9fa;
    }
    
    .custom-modal-title {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
        color: #333;
    }
    
    .custom-modal-close {
        background: transparent;
        border: none;
        font-size: 28px;
        font-weight: 700;
        line-height: 1;
        color: #888;
        cursor: pointer;
        padding: 0;
        margin: 0;
        transition: color 0.2s;
    }
    
    .custom-modal-close:hover {
        color: #333;
    }
    
    .custom-modal-body {
        padding: 20px;
        overflow-y: auto;
        flex: 1;
    }
    
    .custom-modal-footer {
        padding: 15px 20px;
        border-top: 1px solid #e9ecef;
        text-align: right;
        background-color: #f8f9fa;
    }
    
    /* Animación de entrada del modal */
    @keyframes modalFadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    /* Hover suave para la card de filtros */
    .filters-card {
        transition: box-shadow .2s ease, transform .2s ease;
    }
    .filters-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 22px rgba(33,37,41,0.12);
    }
    
    /* Estilos específicos para el modal de detalle de tarifa */
    .rate-detail-modal {
        --brand-blue: #0b99fd;
        --brand-magenta: #bd05dc;
    }

    .rate-detail-modal .info-card,
    .rate-detail-modal .date-card,
    .rate-detail-modal .notes-card,
    .rate-detail-modal .prices-card {
        border: 1px solid #e9ecef;
        border-radius: 10px;
        box-shadow: 0 2px 6px rgba(33,37,41,0.06);
        transition: box-shadow .2s ease, transform .2s ease;
        background-color: #fff;
        overflow: hidden;
    }
    
    /* Acento lateral por card */
    .rate-detail-modal .info-card { border-left: 4px solid var(--brand-blue); padding: 14px 16px; }
    .rate-detail-modal .date-card { border-left: 4px solid var(--brand-magenta); }
    .rate-detail-modal .notes-card { border-left: 4px solid #e0e0e0; }

    /* Hover sutil */
    .rate-detail-modal .info-card:hover,
    .rate-detail-modal .date-card:hover,
    .rate-detail-modal .notes-card:hover,
    .rate-detail-modal .prices-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 22px rgba(33,37,41,0.12);
    }

    /* Encabezados de cards */
    .rate-detail-modal .card-header { 
        background-color: #f8f9fa; 
        padding: .5rem 1rem; 
        border-bottom: 1px solid #e9ecef; 
        border-top-left-radius: 10px; 
        border-top-right-radius: 10px;
    }
    .rate-detail-modal .card-header h6 { 
        margin: 0; 
        display: flex; 
        align-items: center; 
    }
    .rate-detail-modal .card-header h6 .fas { margin-right: .5rem; }
    .rate-detail-modal .date-card .card-header h6 .fas { color: var(--brand-magenta); }
    .rate-detail-modal .notes-card .card-header h6 .fas { color: #6c757d; }

    .rate-detail-modal .detail-item {
        display: flex;
        flex-direction: column;
    }
    
    .rate-detail-modal .detail-label { font-size: .82rem; color: #6c757d; margin-bottom: 4px; display: flex; align-items: center; gap: .375rem; }
    .rate-detail-modal .detail-value { font-weight: 500; overflow-wrap: anywhere; word-break: break-word; }

    /* Badge de tipo con color corporativo */
    .rate-detail-modal #d_tariff_type { background-color: var(--brand-blue) !important; }

    /* Ajustes de paddings horizontales para que no se oculte contenido */
    .rate-detail-modal .date-card .card-body,
    .rate-detail-modal .notes-card .card-body { padding: .75rem 1rem !important; }

    /* Icono de cabecera del modal con color corporativo */
    .rate-detail-modal .custom-modal-header .fa-bolt { color: var(--brand-blue) !important; }
    
    .rate-detail-modal #d_energy_prices tr td:last-child,
    .rate-detail-modal #d_power_prices tr td:last-child {
        text-align: right;
        font-weight: 500;
    }
    
    /* Ajustes responsivos */
    @media (max-width: 767px) {
        .custom-modal-content {
            max-width: 95%;
            max-height: 90vh;
        }
        
        .rate-detail-modal .info-card { padding: 12px; }
        .rate-detail-modal .date-card .card-body,
        .rate-detail-modal .notes-card .card-body { padding: .75rem .75rem !important; }
    }
</style>
{% endblock %}

{% block scripts %}
<script>
    function confirmDelete(rateId, rateName) {
        document.getElementById('deleteTariffName').textContent = rateName;
        document.getElementById('deleteForm').action = "{{ url_for('admin.delete_rate', rate_id=0) }}".replace('0', rateId);
        
        var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        deleteModal.show();
    }
    
    // Poblar dinámicamente un <select> con la lista de comercializadoras
    function populateSupplierSelect(selectId, apiEndpoint, currentValue) {
        const select = document.getElementById(selectId);
        if (!select) return;
        // Limpiar y mantener la opción "Todas"
        select.innerHTML = '';
        const allOpt = document.createElement('option');
        allOpt.value = '';
        allOpt.textContent = 'Todas';
        select.appendChild(allOpt);
        fetch(apiEndpoint)
            .then(r => r.json())
            .then(data => {
                if (data && data.success) {
                    (data.suppliers || []).forEach(s => {
                        const opt = document.createElement('option');
                        opt.value = s;
                        opt.textContent = s;
                        if (currentValue && s === currentValue) opt.selected = true;
                        select.appendChild(opt);
                    });
                }
            })
            .catch(err => console.error('Error cargando comercializadoras:', err));
    }
    
    // Función para configurar el autocomplete
    function setupAutocomplete(inputId, apiEndpoint) {
        const input = document.getElementById(inputId);
        if (!input) return;
        
        // Crear contenedor para las sugerencias
        const suggestionsContainer = document.createElement('div');
        suggestionsContainer.className = 'autocomplete-suggestions';
        suggestionsContainer.style.display = 'none';
        input.parentNode.style.position = 'relative';
        input.parentNode.appendChild(suggestionsContainer);
        
        // Variable para almacenar las opciones
        let options = [];
        
        // Cargar opciones desde la API
        fetch(apiEndpoint)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (apiEndpoint.includes('comercializadoras')) {
                        options = data.suppliers || [];
                    } else {
                        options = data.tariff_types || [];
                    }
                }
            })
            .catch(error => console.error('Error cargando opciones:', error));
        
        // Mostrar sugerencias al escribir
        input.addEventListener('input', function() {
            const value = this.value.toLowerCase();
            suggestionsContainer.innerHTML = '';
            suggestionsContainer.style.display = 'none';
            
            if (!value) return;
            
            const filteredOptions = options.filter(option => 
                option.toLowerCase().includes(value)
            );
            
            if (filteredOptions.length > 0) {
                suggestionsContainer.style.display = 'block';
                filteredOptions.forEach(option => {
                    const item = document.createElement('div');
                    item.className = 'autocomplete-item';
                    item.textContent = option;
                    item.addEventListener('click', function() {
                        input.value = option;
                        suggestionsContainer.style.display = 'none';
                    });
                    suggestionsContainer.appendChild(item);
                });
            }
        });
        
        // Cerrar sugerencias al hacer clic fuera
        document.addEventListener('click', function(e) {
            if (e.target !== input) {
                suggestionsContainer.style.display = 'none';
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Poblar select de comercializadoras dinámicamente
        const supplierSelectEl = document.getElementById('filterSupplierSelect');
        const currentSupplier = supplierSelectEl ? (supplierSelectEl.dataset.currentSupplier || '') : '';
        populateSupplierSelect(
            'filterSupplierSelect',
            '{{ url_for("admin.get_suppliers") }}',
            currentSupplier
        );
        // Autocomplete para tipos de tarifa (se mantiene como input de texto)
        setupAutocomplete('filter_tariff_type', '{{ url_for("admin.get_tariff_types") }}');
        
        // Toggle de filtros: actualizar texto del botón según estado del collapse
        const filtersCollapseEl = document.getElementById('filtersCollapse');
        const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
        if (filtersCollapseEl && toggleFiltersBtn) {
            filtersCollapseEl.addEventListener('shown.bs.collapse', function () {
                const span = toggleFiltersBtn.querySelector('.toggle-text');
                if (span) span.textContent = 'Ocultar filtros';
            });
            filtersCollapseEl.addEventListener('hidden.bs.collapse', function () {
                const span = toggleFiltersBtn.querySelector('.toggle-text');
                if (span) span.textContent = 'Mostrar filtros';
            });
        }
        // Auto submit al cambiar resultados por página
        const perPageSelect = document.getElementById('per_page');
        if (perPageSelect) {
            perPageSelect.addEventListener('change', function() {
                const form = document.getElementById('filtersForm');
                if (form) form.submit();
            });
        }
        // Referencias al modal personalizado
        const customModal = document.getElementById('viewRateModal');
        const modalOverlay = customModal.querySelector('.custom-modal-overlay');
        const modalCloseBtn = document.getElementById('modalCloseBtn');
        const modalCloseButton = document.getElementById('modalCloseButton');
        
        // Funciones para abrir y cerrar el modal personalizado
        function openCustomModal() {
            customModal.style.display = 'block';
            document.body.style.overflow = 'hidden'; // Bloquear scroll
        }
        
        function closeCustomModal() {
            customModal.style.display = 'none';
            document.body.style.overflow = ''; // Restaurar scroll
        }
        
        // Asignar eventos para cerrar el modal
        if (modalCloseBtn) modalCloseBtn.addEventListener('click', closeCustomModal);
        if (modalCloseButton) modalCloseButton.addEventListener('click', closeCustomModal);
        if (modalOverlay) modalOverlay.addEventListener('click', closeCustomModal);
        
        // Cerrar modal con Escape
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape' && customModal.style.display === 'block') {
                closeCustomModal();
            }
        });
        
        // Botones para ver detalles de tarifa
        document.querySelectorAll('.btn-view').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const rateId = this.getAttribute('data-rate-id');
                
                // Petición AJAX para obtener detalles
                fetch(`{{ url_for('admin.rate_detail', rate_id=0) }}`.replace('0', rateId))
                    .then(response => response.json())
                    .then(data => {
                        // Actualizar campos del modal
                        document.getElementById('d_id').textContent = data.rate.id;
                        document.getElementById('d_name').textContent = data.rate.name;
                        document.getElementById('d_supplier').textContent = data.rate.supplier || '-';
                        document.getElementById('d_tariff_type').textContent = data.rate.tariff_type;
                        document.getElementById('d_valid_from').textContent = formatDate(data.rate.valid_from);
                        document.getElementById('d_valid_until').textContent = data.rate.valid_until ? formatDate(data.rate.valid_until) : 'Sin fecha límite';
                        document.getElementById('d_notes').textContent = data.rate.notes || 'Sin notas';
                        
                        // Actualizar tablas de precios
                        updatePriceTable('d_energy_prices', data.rate.energy_prices);
                        updatePriceTable('d_power_prices', data.rate.power_prices);
                        
                        // Mostrar modal personalizado
                        openCustomModal();
                    })
                    .catch(error => console.error('Error:', error));
            });
        });
        
        // Función para formatear fechas
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleDateString('es-ES');
        }
        
        // Función para actualizar tablas de precios
        function updatePriceTable(tableId, prices) {
            const tableBody = document.getElementById(tableId);
            tableBody.innerHTML = '';
            
            if (prices && Object.keys(prices).length > 0) {
                Object.entries(prices).forEach(([period, price]) => {
                    const row = document.createElement('tr');
                    
                    const periodCell = document.createElement('td');
                    const pStr = String(period);
                    periodCell.textContent = pStr.startsWith('P') ? pStr : `P${pStr}`;
                    periodCell.className = 'text-center';
                    row.appendChild(periodCell);
                    
                    const priceCell = document.createElement('td');
                    priceCell.textContent = parseFloat(price).toFixed(6) + ' €';
                    row.appendChild(priceCell);
                    
                    tableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 2;
                cell.textContent = 'No hay datos disponibles';
                cell.className = 'text-center text-muted fst-italic';
                row.appendChild(cell);
                tableBody.appendChild(row);
            }
        }
    });
</script>
{% endblock %}

{% block extra_styles %}
<style>
    .rates-table th {
        background-color: #f8f9fa;
        font-weight: 600;
    }
    
    .empty-state {
        text-align: center;
        padding: 50px 20px;
    }
    
    .empty-icon {
        font-size: 3rem;
        color: #ccc;
        margin-bottom: 20px;
    }
    
    .table-responsive {
        border-radius: 4px;
    }
    
    /* Estilos para el autocompletado */
    .autocomplete-suggestions {
        position: absolute;
        z-index: 1000;
        max-height: 200px;
        overflow-y: auto;
        background: white;
        width: calc(100% - 40px);
        border: 1px solid #ced4da;
        border-radius: 0 0 4px 4px;
        box-shadow: 0 5px 10px rgba(0,0,0,0.1);
        left: 40px;
        top: calc(100% - 1px);
    }
    
    .autocomplete-item {
        padding: 8px 12px;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .autocomplete-item:hover {
        background-color: #f8f9fa;
    }
    
    .autocomplete-item:last-child {
        border-bottom: none;
    }

    /* ===== Modal Detalle de Tarifa: Estilos corporativos y refinados ===== */
    .rate-detail-modal {
        --brand-blue: #0b99fd;
        --brand-magenta: #bd05dc;
    }

    /* Cards base */
    .rate-detail-modal .info-card,
    .rate-detail-modal .date-card,
    .rate-detail-modal .notes-card {
        border: 1px solid #e9ecef;
        border-radius: 10px;
        box-shadow: 0 2px 6px rgba(33,37,41,0.06);
        transition: box-shadow .2s ease, transform .2s ease;
        background-color: #fff;
    }

    /* Acento lateral por card */
    .rate-detail-modal .info-card { border-left: 4px solid var(--brand-blue); padding: 14px 16px; }
    .rate-detail-modal .date-card { border-left: 4px solid var(--brand-magenta); }
    .rate-detail-modal .notes-card { border-left: 4px solid #e0e0e0; }

    /* Hover sutil */
    .rate-detail-modal .info-card:hover,
    .rate-detail-modal .date-card:hover,
    .rate-detail-modal .notes-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 22px rgba(33,37,41,0.12);
    }

    /* Encabezados de cards */
    .rate-detail-modal .card-header { 
        background-color: #f8f9fa; 
        padding: .5rem 1rem; 
        border-bottom: 1px solid #e9ecef; 
        border-top-left-radius: 10px; 
        border-top-right-radius: 10px;
    }
    .rate-detail-modal .card-header h6 { 
        margin: 0; 
        display: flex; 
        align-items: center; 
    }
    .rate-detail-modal .card-header h6 .fas { margin-right: .5rem; }
    .rate-detail-modal .date-card .card-header h6 .fas { color: var(--brand-magenta); }
    .rate-detail-modal .notes-card .card-header h6 .fas { color: #6c757d; }

    /* Etiquetas y valores */
    .rate-detail-modal .detail-item { display: flex; flex-direction: column; }
    .rate-detail-modal .detail-label { font-size: .82rem; color: #6c757d; margin-bottom: 4px; display: flex; align-items: center; gap: .375rem; }
    .rate-detail-modal .detail-value { font-weight: 500; overflow-wrap: anywhere; word-break: break-word; }

    /* Badge de tipo con color corporativo */
    .rate-detail-modal #d_tariff_type { background-color: var(--brand-blue) !important; }

    /* Ajustes de paddings horizontales para que no se oculte contenido */
    .rate-detail-modal .date-card .card-body,
    .rate-detail-modal .notes-card .card-body { padding: .75rem 1rem !important; }

    /* Icono de cabecera del modal con color corporativo */
    .rate-detail-modal .custom-modal-header .fa-bolt { color: var(--brand-blue) !important; }

    /* Responsive */
    @media (max-width: 767.98px) {
        .rate-detail-modal .info-card { padding: 12px; }
        .rate-detail-modal .date-card .card-body,
        .rate-detail-modal .notes-card .card-body { padding: .75rem .75rem !important; }
    }
</style>
{% endblock %}
