@extends('layouts.app')

@section('title', 'Dashboard Maestro')
@section('page-title', 'Panel Maestro')

@section('page-actions')
<div class="d-flex gap-2">
    <a href="{{ route('admin.monitor') }}" class="btn btn-outline-primary btn-sm">
        <i class="fas fa-wave-square me-1"></i> Monitor en vivo
    </a>
    <a href="{{ route('admin.transacciones') }}" class="btn btn-primary btn-sm">
        <i class="fas fa-coins me-1"></i> Revisar transacciones
    </a>
</div>
@endsection

@section('content')
<div class="row g-3">
    <div class="col-xl-3 col-lg-4 col-md-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 activos</p>
                        <h3 class="fw-semibold mb-0">{{ number_format($metrics['total_scawatts']) }}</h3>
                    </div>
                    <span class="icon-circle bg-primary-subtle text-primary">
                        <i class="fas fa-solar-panel"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">En marketplace: <span class="fw-semibold">{{ number_format($metrics['scawatts_marketplace']) }}</span></p>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-4 col-md-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 total ScaWatts</p>
                        <h3 class="fw-semibold mb-0">{{ $metrics['valor_total_actual'] }}</h3>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success">
                        <i class="fas fa-hand-holding-dollar"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">Inversión inicial: <span class="fw-semibold">{{ $metrics['valor_total_inicial'] }}</span></p>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-4 col-md-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 acumulada</p>
                        <h3 class="fw-semibold mb-0">{{ $metrics['valorizacion_total'] }}</h3>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning">
                        <i class="fas fa-chart-line"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">Carga media kWh: <span class="fw-semibold">{{ $metrics['kwh_total'] }}</span></p>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-4 col-md-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">Usuarios</p>
                        <h3 class="fw-semibold mb-0">{{ number_format($metrics['total_usuarios']) }}</h3>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info">
                        <i class="fas fa-users"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">Nuevos últimos 30 días: <span class="fw-semibold">{{ number_format($metrics['usuarios_ultimos_30']) }}</span></p>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-4 col-md-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">Retiros pendientes</p>
                        <h3 class="fw-semibold mb-0">{{ number_format($metrics['retiros_pendientes']) }}</h3>
                    </div>
                    <span class="icon-circle bg-danger-subtle text-danger">
                        <i class="fas fa-arrow-up-long"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">Valor acumulado: <span class="fw-semibold">{{ $metrics['retiros_pendientes_monto'] }}</span></p>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-lg-4 col-md-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">Depósitos pendientes</p>
                        <h3 class="fw-semibold mb-0">{{ number_format($metrics['depositos_pendientes']) }}</h3>
                    </div>
                    <span class="icon-circle bg-secondary-subtle text-secondary">
                        <i class="fas fa-arrow-down-long"></i>
                    </span>
                </div>
                <p class="mt-3 mb-0 text-muted small">Valor acumulado: <span class="fw-semibold">{{ $metrics['depositos_pendientes_monto'] }}</span></p>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mt-1">
    <div class="col-xl-7">
        <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">Granjas más activas</h6>
                    <small class="text-muted">ScaWatts y valoración acumulada</small>
                </div>
                <span class="badge bg-primary-subtle text-primary">Top 5</span>
            </div>
            <div class="card-body">
                @if(empty($charts['granjas']['labels']))
                    <p class="text-muted mb-0">Aún no hay datos de granjas con ScaWatts asociados.</p>
                @else
                    <canvas id="granjasChart" height="220"></canvas>
                @endif
            </div>
        </div>
    </div>
    <div class="col-xl-5">
        <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">Estado financiero inmediato</h6>
                    <small class="text-muted">Depósitos vs Retiros en proceso</small>
                </div>
                <span class="badge bg-dark-subtle text-dark">Tiempo real</span>
            </div>
            <div class="card-body">
                <canvas id="finanzasChart" height="200"></canvas>
                <div class="d-flex justify-content-between mt-3">
                    <div>
                        <span class="badge bg-secondary"></span>
                        <span class="ms-2 text-muted small">Depósitos pendientes</span>
                    </div>
                    <div class="text-end">
                        <p class="mb-0 fw-semibold">{{ $metrics['depositos_pendientes_monto'] }}</p>
                        <small class="text-muted">{{ number_format($metrics['depositos_pendientes']) }} solicitudes</small>
                    </div>
                </div>
                <div class="d-flex justify-content-between mt-3">
                    <div>
                        <span class="badge bg-danger"></span>
                        <span class="ms-2 text-muted small">Retiros pendientes</span>
                    </div>
                    <div class="text-end">
                        <p class="mb-0 fw-semibold">{{ $metrics['retiros_pendientes_monto'] }}</p>
                        <small class="text-muted">{{ number_format($metrics['retiros_pendientes']) }} solicitudes</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mt-1">
    <div class="col-xl-6">
        <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">
                <h6 class="mb-0">Últimos retiros</h6>
                <a href="{{ route('admin.transacciones') }}" class="btn btn-sm btn-outline-secondary">Ver todo</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Usuario</th>
                                <th>Monto</th>
                                <th>Estado</th>
                                <th>Fecha</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($recentRetiros as $retiro)
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $retiro->usuario->nombre ?? 'Usuario eliminado' }}</div>
                                    <small class="text-muted">ID {{ $retiro->id }}</small>
                                </td>
                                <td>${{ number_format($retiro->monto, 0, ',', '.') }}</td>
                                <td>
                                    <span class="badge bg-{{ $retiro->estado === 'pendiente' ? 'warning' : ($retiro->estado === 'completado' ? 'success' : 'secondary') }}">{{ ucfirst($retiro->estado) }}</span>
                                </td>
                                <td><small class="text-muted">{{ $retiro->created_at?->format('d M Y H:i') ?? 'N/D' }}</small></td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">Sin movimientos recientes</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-6">
        <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">
                <h6 class="mb-0">Últimos depósitos</h6>
                <a href="{{ route('admin.transacciones') }}" class="btn btn-sm btn-outline-secondary">Ver todo</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Usuario</th>
                                <th>Monto</th>
                                <th>Estado</th>
                                <th>Fecha</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($recentDepositos as $deposito)
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $deposito->usuario->nombre ?? 'Usuario eliminado' }}</div>
                                    <small class="text-muted">Ref {{ $deposito->referencia_pago ?? 'N/D' }}</small>
                                </td>
                                <td>${{ number_format($deposito->monto, 0, ',', '.') }}</td>
                                <td>
                                    <span class="badge bg-{{ $deposito->estado === 'pendiente' ? 'warning' : ($deposito->estado === 'aprobado' ? 'success' : 'secondary') }}">{{ ucfirst($deposito->estado) }}</span>
                                </td>
                                <td><small class="text-muted">{{ $deposito->created_at?->format('d M Y H:i') ?? 'N/D' }}</small></td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">Sin movimientos recientes</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mt-1">
    <div class="col-xl-6">
        <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">
                <h6 class="mb-0">Top usuarios por saldo</h6>
                <span class="badge bg-success-subtle text-success">Disponible</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($topUsuarios as $usuario)
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <div class="fw-semibold">{{ $usuario->nombre ?? 'Usuario eliminado' }}</div>
                                <small class="text-muted">Saldo total: ${{ number_format($usuario->saldo_total ?? 0, 0, ',', '.') }}</small>
                            </div>
                            <div class="text-end">
                                <span class="badge bg-primary">Disponible ${{ number_format($usuario->saldo_disponible ?? 0, 0, ',', '.') }}</span>
                            </div>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted">Sin datos disponibles</li>
                    @endforelse
                </ul>
            </div>
        </div>
    </div>
    <div class="col-xl-6">
        <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">
                <h6 class="mb-0">Marketplace (últimas publicaciones)</h6>
                <a href="{{ route('admin.marketplace') }}" class="btn btn-sm btn-outline-secondary">Gestionar</a>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($marketplaceReciente as $pub)
                        <li class="list-group-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <div class="fw-semibold">{{ $pub->scawatt->scawatt_id ?? 'ScaWatt desconocido' }}</div>
                                    <small class="text-muted">{{ $pub->vendedor->nombre ?? 'Vendedor N/D' }} · ${{ number_format($pub->precio_venta ?? 0, 0, ',', '.') }}</small>
                                </div>
                                <span class="badge bg-{{ $pub->estado === 'en_venta' ? 'primary' : ($pub->estado === 'vendido' ? 'success' : 'secondary') }}">{{ ucwords(str_replace('_', ' ', $pub->estado)) }}</span>
                            </div>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted">Sin publicaciones recientes</li>
                    @endforelse
                </ul>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const granjasChartEl = document.getElementById('granjasChart');
        if (granjasChartEl && {{ count($charts['granjas']['labels']) }} > 0) {
            new Chart(granjasChartEl, {
                type: 'bar',
                data: {
                    labels: {!! json_encode($charts['granjas']['labels']) !!},
                    datasets: [
                        {
                            label: 'ScaWatts',
                            data: {!! json_encode($charts['granjas']['scawatts']) !!},
                            backgroundColor: 'rgba(99, 102, 241, 0.75)',
                            borderRadius: 6,
                            maxBarThickness: 36
                        },
                        {
                            label: 'Valor actual (COP)',
                            data: {!! json_encode($charts['granjas']['valor_total']) !!},
                            backgroundColor: 'rgba(16, 185, 129, 0.5)',
                            borderRadius: 6,
                            maxBarThickness: 36,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { intersect: false, mode: 'index' },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: value => value.toLocaleString('es-CO')
                            }
                        },
                        y1: {
                            beginAtZero: true,
                            position: 'right',
                            grid: { drawOnChartArea: false },
                            ticks: {
                                callback: value => '$' + Number(value).toLocaleString('es-CO')
                            }
                        }
                    }
                }
            });
        }

        const finanzasChartEl = document.getElementById('finanzasChart');
        if (finanzasChartEl) {
            new Chart(finanzasChartEl, {
                type: 'doughnut',
                data: {
                    labels: ['Depósitos pendientes', 'Retiros pendientes'],
                    datasets: [{
                        data: [{{ $metrics['depositos_pendientes_monto_raw'] }}, {{ $metrics['retiros_pendientes_monto_raw'] }}],
                        backgroundColor: ['#6c757d', '#dc3545'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    cutout: '65%',
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }
    });
</script>
@endpush
