<?php

use yii\helpers\Html;
use yii\helpers\Url;

/** @var yii\web\View $this */
/** @var array $dashboard */

$this->title = Yii::t('app', 'Queue Monitor');
$this->params['breadcrumbs'][] = $this->title;

$summary = $dashboard['summary'] ?? ['total' => 0, 'healthy' => 0, 'warning' => 0, 'critical' => 0, 'unknown' => 0];
$statusStyles = [
    'healthy' => 'success',
    'warning' => 'warning',
    'critical' => 'danger',
    'unknown' => 'secondary',
];

$formatTimestamp = static function (?int $timestamp): string {
    return $timestamp ? date('Y-m-d H:i:s', $timestamp) : '-';
};

$formatDuration = static function (?int $seconds): string {
    if ($seconds === null) {
        return '-';
    }

    if ($seconds < 60) {
        return $seconds . 's';
    }

    $minutes = floor($seconds / 60);
    if ($minutes < 60) {
        return $minutes . 'm';
    }

    $hours = floor($minutes / 60);
    $minutesRemainder = $minutes % 60;

    if ($hours < 24) {
        return $hours . 'h ' . $minutesRemainder . 'm';
    }

    $days = floor($hours / 24);
    $hoursRemainder = $hours % 24;

    return $days . 'd ' . $hoursRemainder . 'h';
};
?>

<div class="queue-monitor-index">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h1 class="mb-0"><?= Html::encode($this->title) ?></h1>
        <div>
            <?= Html::a('Refresh', ['index'], ['class' => 'btn btn-primary btn-sm']) ?>
            <?= Html::a('JSON Status', ['status'], ['class' => 'btn btn-outline-secondary btn-sm', 'target' => '_blank']) ?>
        </div>
    </div>

    <div class="text-muted mb-3">
        Generated: <?= Html::encode($formatTimestamp($dashboard['generatedAt'] ?? null)) ?>
    </div>

    <div class="row mb-3">
        <div class="col-md-2 col-6 mb-2">
            <div class="card"><div class="card-body py-2"><strong>Total:</strong> <?= (int)$summary['total'] ?></div></div>
        </div>
        <div class="col-md-2 col-6 mb-2">
            <div class="card border-success"><div class="card-body py-2"><strong class="text-success">Healthy:</strong> <?= (int)$summary['healthy'] ?></div></div>
        </div>
        <div class="col-md-2 col-6 mb-2">
            <div class="card border-warning"><div class="card-body py-2"><strong class="text-warning">Warning:</strong> <?= (int)$summary['warning'] ?></div></div>
        </div>
        <div class="col-md-2 col-6 mb-2">
            <div class="card border-danger"><div class="card-body py-2"><strong class="text-danger">Critical:</strong> <?= (int)$summary['critical'] ?></div></div>
        </div>
        <div class="col-md-2 col-6 mb-2">
            <div class="card border-secondary"><div class="card-body py-2"><strong class="text-secondary">Unknown:</strong> <?= (int)$summary['unknown'] ?></div></div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-sm table-bordered table-striped">
            <thead>
                <tr>
                    <th>Queue Component</th>
                    <th>Channel</th>
                    <th>Status</th>
                    <th>Pending</th>
                    <th>Running</th>
                    <th>Stale Running</th>
                    <th>Oldest Pending</th>
                    <th>Supervisor</th>
                    <th>Heartbeat</th>
                    <th>Controls</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach (($dashboard['queues'] ?? []) as $queue): ?>
                <?php $status = $queue['status'] ?? 'unknown'; ?>
                <tr>
                    <td>
                        <strong><?= Html::encode($queue['component']) ?></strong>
                        <?php if (!empty($queue['componentMissing'])): ?>
                            <div><span class="badge badge-danger">Missing Component</span></div>
                        <?php endif; ?>
                        <?php if (!empty($queue['class'])): ?>
                            <div class="small text-muted"><?= Html::encode($queue['class']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td><?= Html::encode($queue['channel']) ?></td>
                    <td>
                        <span class="badge badge-<?= $statusStyles[$status] ?? 'secondary' ?>">
                            <?= Html::encode(strtoupper($status)) ?>
                        </span>
                        <?php if (!empty($queue['notes'])): ?>
                            <div class="small mt-1 text-muted">
                                <?= implode('<br>', array_map(static function ($note) {
                                    return Html::encode($note);
                                }, $queue['notes'])) ?>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td><?= (int)$queue['pending'] ?></td>
                    <td><?= (int)$queue['running'] ?></td>
                    <td><?= (int)$queue['staleRunning'] ?></td>
                    <td>
                        <div><?= Html::encode($formatDuration($queue['oldestPendingAge'])) ?></div>
                        <div class="small text-muted"><?= Html::encode($formatTimestamp($queue['oldestPendingAt'])) ?></div>
                    </td>
                    <td>
                        <?php if (!empty($queue['requiresSupervisor'])): ?>
                            <span class="badge badge-info">Required</span>
                            <div class="small mt-1">
                                <?php if (!empty($queue['supervisorConfigured'])): ?>
                                    <span class="text-success">Config detected</span>
                                <?php else: ?>
                                    <span class="text-danger">Config missing</span>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <span class="badge badge-light">Optional</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div><?= Html::encode($formatDuration($queue['heartbeatAge'])) ?></div>
                        <div class="small text-muted"><?= Html::encode($formatTimestamp($queue['heartbeatAt'])) ?></div>
                    </td>
                    <td>
                        <div class="btn-group-vertical btn-group-sm mb-1" role="group">
                            <?= Html::a('Pending', ['/queue/pending', 'Queuesearch[channel]' => $queue['channel']], ['class' => 'btn btn-outline-primary']) ?>
                            <?= Html::a('Running', ['/queue/running', 'Queuesearch[channel]' => $queue['channel']], ['class' => 'btn btn-outline-primary']) ?>
                            <?= Html::a('Jobs', ['/queue/joblist'], ['class' => 'btn btn-outline-primary']) ?>
                        </div>
                        <div class="small text-muted">
                            <?= Html::encode($queue['commands']['listen'] ?? '') ?><br>
                            <?= Html::encode($queue['commands']['log'] ?? '') ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
