@extends('layouts.app')

@section('title', 'ScaWatts')
@section('page-title', 'Inventario de ScaWatts')
@section('page-subtitle', 'Controla seriales, valorizaciones y asignaciones por granja en tiempo real')

@section('page-actions')
<div class="d-flex gap-2">
    <a href="{{ route('admin.marketplace') }}" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-store me-1"></i> Marketplace
    </a>
    <a href="{{ route('admin.granjas') }}" class="btn btn-sm btn-secondary">
        <i class="fas fa-seedling me-1"></i> Granjas
    </a>
</div>
@endsection

@section('content')
@php
    $estadoOptions = [
        'todos' => 'Todos los estados',
        'activo' => 'Activos',
        'marketplace' => 'En marketplace',
        'reservado' => 'Reservados',
        'vendido' => 'Vendidos',
        'bloqueado' => 'Bloqueados',
    ];

    $tipoOptions = ['todos' => 'Todos los tipos'];
    foreach ($porTipo as $tipoRow) {
        $clave = $tipoRow->tipo ?: 'sin_tipo';
        $tipoOptions[$clave] = ucfirst(str_replace('_', ' ', $clave));
    }

    $ordenOptions = [
        'recientes' => 'Más recientes',
        'valor_desc' => 'Valor mayor a menor',
        'valor_asc' => 'Valor menor a mayor',
        'kwh_desc' => 'kWh mayor a menor',
        'kwh_asc' => 'kWh menor a mayor',
        'valorizacion' => 'Mayor valorización',
    ];
@endphp

<div class="row g-3 mb-1">
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Total ScaWatts</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['total']) }}</h4>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning"><i class="fas fa-solar-panel"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Activos</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['activos']) }}</h4>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success"><i class="fas fa-bolt"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">En marketplace</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['marketplace']) }}</h4>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info"><i class="fas fa-store"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Valor actual</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['valor_actual'] }}</h4>
                    </div>
                    <span class="icon-circle bg-secondary-subtle text-secondary"><i class="fas fa-coins"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Valorización</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['valorizacion'] }}</h4>
                    </div>
                    <span class="icon-circle bg-dark-subtle text-dark"><i class="fas fa-chart-line"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">kWh administrados</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['kwh_total'] }} kWh</h4>
                    </div>
                    <span class="icon-circle bg-primary-subtle text-primary"><i class="fas fa-battery-full"></i></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-xl-3 col-md-4">
                <label for="estado" class="form-label small text-uppercase text-muted mb-1">Estado</label>
                <select id="estado" name="estado" class="form-select form-select-sm">
                    @foreach($estadoOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['estado'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xl-3 col-md-4">
                <label for="granja" class="form-label small text-uppercase text-muted mb-1">Granja</label>
                <select id="granja" name="granja" class="form-select form-select-sm">
                    <option value="todas" @selected($filtros['granja'] === 'todas')>Todas las granjas</option>
                    @foreach($granjas as $granja)
                        <option value="{{ $granja->id }}" @selected($filtros['granja'] == $granja->id)>{{ $granja->nombre }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xl-2 col-md-4">
                <label for="tipo" class="form-label small text-uppercase text-muted mb-1">Tipo</label>
                <select id="tipo" name="tipo" class="form-select form-select-sm">
                    @foreach($tipoOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['tipo'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xl-2 col-md-4">
                <label for="orden" class="form-label small text-uppercase text-muted mb-1">Orden</label>
                <select id="orden" name="orden" class="form-select form-select-sm">
                    @foreach($ordenOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['orden'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xl-1 col-md-4">
                <label for="por_pagina" class="form-label small text-uppercase text-muted mb-1">Por página</label>
                <input type="number" min="10" max="100" id="por_pagina" name="por_pagina" value="{{ $filtros['por_pagina'] }}" class="form-control form-control-sm">
            </div>
            <div class="col-xl-3 col-md-4">
                <label for="q" class="form-label small text-uppercase text-muted mb-1">Buscar</label>
                <input type="search" id="q" name="q" value="{{ $filtros['q'] }}" class="form-control form-control-sm" placeholder="Serial, usuario, correo...">
            </div>
            <div class="col-xl-1 col-md-3 d-flex gap-2">
                <button type="submit" class="btn btn-sm btn-primary flex-fill">
                    <i class="fas fa-filter me-1"></i> Aplicar
                </button>
                <a href="{{ route('admin.scawatts') }}" class="btn btn-sm btn-outline-secondary" title="Limpiar filtros">
                    <i class="fas fa-rotate-right"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <div class="col-xxl-9 col-xl-8">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-0">Inventario detallado</h6>
                    <small class="text-muted">Mostrando {{ $scawatts->firstItem() ?? 0 }}-{{ $scawatts->lastItem() ?? 0 }} de {{ $scawatts->total() }} registros</small>
                </div>
                <span class="badge bg-primary-subtle text-primary">{{ strtoupper($filtros['estado']) }}</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>ScaWatt</th>
                                <th>Propietario</th>
                                <th>Granja</th>
                                <th>kWh</th>
                                <th>Valor</th>
                                <th class="text-center">Estado</th>
                                <th>Inicio</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($scawatts as $scawatt)
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $scawatt->scawatt_id ?? 'Sin serial' }}</div>
                                    <small class="text-muted">Tipo: {{ ucfirst($scawatt->tipo ?? 'N/D') }}</small>
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ $scawatt->usuario?->nombre ?? 'Sin asignar' }}</div>
                                    <small class="text-muted">{{ $scawatt->usuario?->email ?? 'Sin correo' }}</small>
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ $scawatt->granja?->nombre ?? 'Sin granja' }}</div>
                                    <small class="text-muted">{{ $scawatt->granja?->departamento ?? 'N/D' }} · {{ $scawatt->granja?->municipio ?? 'N/D' }}</small>
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ number_format((float) ($scawatt->kwh_asignados ?? 0), 2, ',', '.') }} kWh</div>
                                </td>
                                <td>
                                    <div class="fw-semibold">Actual: ${{ number_format((float) ($scawatt->valor_actual ?? 0), 0, ',', '.') }}</div>
                                    <small class="text-muted">Inicial: ${{ number_format((float) ($scawatt->valor_inicial ?? 0), 0, ',', '.') }}</small>
                                </td>
                                <td class="text-center">
                                    <span class="badge {{ $scawatt->estado === 'activo' ? 'bg-success' : ($scawatt->estado === 'marketplace' ? 'bg-info' : ($scawatt->estado === 'vendido' ? 'bg-secondary' : 'bg-warning text-dark')) }}">
                                        {{ ucfirst(str_replace('_', ' ', $scawatt->estado ?? 'N/D')) }}
                                    </span>
                                </td>
                                <td>
                                    <div class="fw-semibold">{{ $scawatt->fecha_inicio?->format('d M Y') ?? $scawatt->created_at?->format('d M Y') ?? 'N/D' }}</div>
                                    <small class="text-muted">Actualización: {{ $scawatt->updated_at?->diffForHumans() ?? 'N/D' }}</small>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="text-center text-muted py-5">No se encontraron ScaWatts con los filtros seleccionados.</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white border-0">
                <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-2">
                    <small class="text-muted">Valor inicial histórico: {{ $stats['valor_inicial'] }}</small>
                    {{ $scawatts->links('pagination::bootstrap-5') }}
                </div>
            </div>
        </div>
    </div>
    <div class="col-xxl-3 col-xl-4">
        <div class="card shadow-sm border-0 mb-3">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Distribución por estado</h6>
                <span class="badge bg-dark-subtle text-dark">{{ number_format($stats['total']) }}</span>
            </div>
            <div class="card-body">
                @forelse($porEstado as $fila)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div>
                            <div class="fw-semibold">{{ ucfirst(str_replace('_', ' ', $fila['estado'])) }}</div>
                            <small class="text-muted">{{ $fila['valor'] }}</small>
                        </div>
                        <span class="badge bg-light text-dark">{{ number_format($fila['total']) }}</span>
                    </div>
                @empty
                    <p class="text-muted mb-0">Sin datos para mostrar.</p>
                @endforelse
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Granjas más activas</h6>
                <span class="badge bg-info-subtle text-info">{{ $topGranjas->count() }}</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($topGranjas as $granja)
                        <li class="list-group-item d-flex justify-content-between align-items-start">
                            <div>
                                <div class="fw-semibold">{{ $granja->nombre }}</div>
                                <small class="text-muted">ScaWatts: {{ number_format($granja->scawatts_count) }}</small>
                            </div>
                            <div class="text-end">
                                <span class="badge bg-primary">${{ number_format((float) $granja->scawatts_sum_valor_actual, 0, ',', '.') }}</span>
                                <div><small class="text-muted">kWh: {{ number_format((float) ($granja->kwh_total ?? 0), 2, ',', '.') }}</small></div>
                            </div>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted py-4">Sin información disponible</li>
                    @endforelse
                </ul>
            </div>
        </div>
    </div>
</div>
@endsection
