@extends('layouts.app')

@section('title', 'Granjas solares')
@section('page-title', 'Granjas solares')
@section('page-subtitle', 'Monitorea la capacidad instalada, producción y ScaWatts vinculados por granja')

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

@section('content')
@php
    $estadoOptions = [
        'todas' => 'Todos los estados',
        'operativa' => 'Operativas',
        'construccion' => 'En construcción',
        'planificada' => 'Planificadas',
        'mantenimiento' => 'En mantenimiento',
    ];

    $ordenOptions = [
        'recientes' => 'Más recientes',
        'capacidad' => 'Mayor capacidad',
        'produccion' => 'Mayor producción',
        'scawatts' => 'Más ScaWatts',
        'valor' => 'Mayor valorización',
    ];

    $estadoBadges = [
        'operativa' => 'bg-success',
        'construccion' => 'bg-warning text-dark',
        'planificada' => 'bg-info text-dark',
        'mantenimiento' => 'bg-secondary',
    ];
@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">Granjas registradas</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['total']) }}</h4>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success"><i class="fas fa-seedling"></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">Granjas operativas</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['operativas']) }}</h4>
                    </div>
                    <span class="icon-circle bg-primary-subtle text-primary"><i class="fas fa-sun"></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">Capacidad instalada</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['capacidad_total'] }} MW</h4>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info"><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">Producción anual</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['produccion_total'] }} MWh</h4>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning"><i class="fas fa-chart-area"></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">ScaWatts vinculados</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['scawatts']) }}</h4>
                    </div>
                    <span class="icon-circle bg-secondary-subtle text-secondary"><i class="fas fa-cubes"></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 ScaWatts</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['valor_scawatts'] }}</h4>
                    </div>
                    <span class="icon-circle bg-dark-subtle text-dark"><i class="fas fa-coins"></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="departamento" class="form-label small text-uppercase text-muted mb-1">Departamento</label>
                <select id="departamento" name="departamento" class="form-select form-select-sm">
                    <option value="todos" @selected($filtros['departamento'] === 'todos')>Todos</option>
                    @foreach($departamentos as $dep)
                        <option value="{{ $dep }}" @selected($filtros['departamento'] === $dep)>{{ $dep }}</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-2 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="6" max="60" id="por_pagina" name="por_pagina" value="{{ $filtros['por_pagina'] }}" class="form-control form-control-sm">
            </div>
            <div class="col-xl-2 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="Nombre, municipio, categoría...">
            </div>
            <div class="col-xl-2 col-md-4 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.granjas') }}" 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">Listado de granjas</h6>
                    <small class="text-muted">Mostrando {{ $granjas->firstItem() ?? 0 }}-{{ $granjas->lastItem() ?? 0 }} de {{ $granjas->total() }} registros</small>
                </div>
                <span class="badge bg-primary-subtle text-primary">{{ strtoupper($filtros['estado']) }}</span>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    @forelse($granjas as $granja)
                        @php
                            $badgeClass = $estadoBadges[$granja->estado] ?? 'bg-dark';
                            $valorActual = $granja->scawatts_sum_valor_actual ?? 0;
                        @endphp
                        <div class="col-xl-6">
                            <div class="card border-0 shadow-sm h-100">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <h5 class="mb-1">{{ $granja->nombre }}</h5>
                                            <div class="text-muted small">
                                                <i class="fas fa-location-dot me-1"></i>{{ $granja->municipio ?? 'Municipio N/D' }}, {{ $granja->departamento ?? 'Departamento N/D' }}
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <span class="badge {{ $badgeClass }}">{{ $granja->estado_formateado ?? ucfirst($granja->estado ?? 'N/D') }}</span>
                                            @if($granja->categoria)
                                                <div><small class="badge bg-light text-dark mt-1">{{ ucfirst(str_replace('_', ' ', $granja->categoria)) }}</small></div>
                                            @endif
                                        </div>
                                    </div>
                                    <div class="row g-2 mb-2">
                                        <div class="col-6">
                                            <div class="small text-muted">Capacidad</div>
                                            <div class="fw-semibold">{{ number_format((float) ($granja->capacidad_mw ?? 0), 2, ',', '.') }} MW</div>
                                        </div>
                                        <div class="col-6">
                                            <div class="small text-muted">Producción anual</div>
                                            <div class="fw-semibold">{{ number_format((float) ($granja->produccion_estimada_anual ?? 0), 2, ',', '.') }} MWh</div>
                                        </div>
                                        <div class="col-6">
                                            <div class="small text-muted">ScaWatts asociados</div>
                                            <div class="fw-semibold">{{ number_format($granja->scawatts_count) }}</div>
                                        </div>
                                        <div class="col-6">
                                            <div class="small text-muted">Valor portafolio</div>
                                            <div class="fw-semibold">${{ number_format((float) $valorActual, 0, ',', '.') }}</div>
                                        </div>
                                    </div>
                                    <p class="text-muted small mb-0">
                                        <i class="fas fa-calendar me-1"></i>Inicio operación: {{ $granja->fecha_inicio_operacion?->format('d M Y') ?? 'N/D' }} · Vida útil: {{ $granja->vida_util_años ? $granja->vida_util_años . ' años' : 'N/D' }}
                                    </p>
                                </div>
                                <div class="card-footer bg-white border-0 d-flex justify-content-between align-items-center">
                                    <div class="text-muted small">Actualizada {{ $granja->updated_at?->diffForHumans() ?? 'N/D' }}</div>
                                    <div class="btn-group">
                                        <a href="{{ route('admin.scawatts', ['granja' => $granja->id]) }}" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-hashtag me-1"></i>ScaWatts
                                        </a>
                                        @if($granja->latitud && $granja->longitud)
                                            <a href="https://maps.google.com/?q={{ $granja->latitud }},{{ $granja->longitud }}" class="btn btn-sm btn-outline-secondary" target="_blank" rel="noopener">
                                                <i class="fas fa-map-marked-alt"></i>
                                            </a>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="col-12">
                            <div class="text-center text-muted py-5">
                                No encontramos granjas con los filtros seleccionados.
                            </div>
                        </div>
                    @endforelse
                </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">Capacidad consolidada: {{ $stats['capacidad_total'] }} MW</small>
                    {{ $granjas->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">Estados operativos</h6>
                <span class="badge bg-dark-subtle text-dark">{{ number_format($stats['total']) }}</span>
            </div>
            <div class="card-body">
                @forelse($segmentacionEstados as $segmento)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div class="fw-semibold">{{ ucfirst(str_replace('_', ' ', $segmento->estado ?? 'N/D')) }}</div>
                        <span class="badge bg-light text-dark">{{ number_format($segmento->total) }}</span>
                    </div>
                @empty
                    <p class="text-muted mb-0">Sin datos disponibles.</p>
                @endforelse
            </div>
        </div>

        <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">Top producción anual</h6>
                <span class="badge bg-info-subtle text-info">{{ $topProduccion->count() }}</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($topProduccion as $item)
                        <li class="list-group-item d-flex justify-content-between align-items-start">
                            <div>
                                <div class="fw-semibold">{{ $item->nombre }}</div>
                                <small class="text-muted">Capacidad: {{ number_format((float) ($item->capacidad_mw ?? 0), 2, ',', '.') }} MW</small>
                            </div>
                            <div class="text-end">
                                <span class="badge bg-success">{{ number_format((float) ($item->produccion_estimada_anual ?? 0), 2, ',', '.') }} MWh</span>
                            </div>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted py-4">Sin información disponible</li>
                    @endforelse
                </ul>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-header bg-white border-0">
                <h6 class="mb-0">Notas operativas</h6>
            </div>
            <div class="card-body">
                <p class="text-muted small mb-2"><i class="fas fa-circle-info me-1"></i>Usa el atajo <code>Alt + K</code> para filtrar rápidamente por departamento en el buscador.</p>
                <p class="text-muted small mb-2"><i class="fas fa-circle-info me-1"></i>Los valores de portafolio provienen del total de ScaWatts activos en cada granja.</p>
                <p class="text-muted small mb-0"><i class="fas fa-circle-info me-1"></i>Haz clic en el ícono de mapa para validar coordenadas en Google Maps.</p>
            </div>
        </div>
    </div>
</div>
@endsection
