<?= $this->extend('layouts/dashboard') ?>

<?= $this->section('content') ?>
<?php
$selectedScopes = old('scopes') ?? [];
$scopeAliases = [
    'facilities:read' => 'sites:read',
    'facilities:write' => 'sites:write',
    'meters:read' => 'turbines:read',
    'meters:write' => 'turbines:write',
    'readings:read' => 'maintenance:read',
    'readings:write' => 'maintenance:write',
    'certificates:read' => 'maintenance:read',
    'certificates:write' => 'maintenance:write',
    'verify:read' => 'audit:read',
];
?>
<section class="grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_420px]">
    <article class="rounded-[30px] border border-white/10 bg-gradient-to-br from-sky-500/18 via-slate-900 to-cyan-500/10 p-6 shadow-glow">
        <div class="inline-flex rounded-full border border-sky-400/30 bg-sky-400/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-sky-100">API access</div>
        <h1 class="mt-4 text-3xl font-semibold tracking-tight text-white sm:text-4xl">API Keys</h1>
        <p class="mt-4 max-w-3xl text-sm leading-7 text-slate-300">Emite Bearer tokens por tenant com scopes para sites, turbines, maintenance, audit e blockchain.</p>

        <?php if (! empty($newApiKeyToken)): ?>
            <div class="mt-6 rounded-3xl border border-cyan-400/20 bg-cyan-400/10 p-5">
                <div class="text-xs uppercase tracking-[0.22em] text-cyan-100">Novo token</div>
                <div class="mt-3 overflow-x-auto rounded-2xl border border-white/10 bg-slate-950/50 px-4 py-4 font-mono text-sm text-white"><?= esc($newApiKeyToken) ?></div>
                <p class="mt-3 text-sm text-slate-300">Copia agora. Por segurança, a chave em texto simples só é mostrada uma vez.</p>
            </div>
        <?php endif; ?>
    </article>

    <article class="rounded-[30px] border border-white/10 bg-white/5 p-6 backdrop-blur">
        <h2 class="text-xl font-semibold text-white">Emitir nova API key</h2>
        <p class="mt-1 text-sm text-slate-400">Cada chave fica ligada ao tenant ativo e deve ter apenas os scopes de que realmente precisa.</p>

        <?php if (session('errors')): ?>
            <ul class="mt-4 rounded-3xl border border-rose-400/20 bg-rose-400/10 p-5 text-sm text-rose-100">
                <?php foreach (session('errors') as $error): ?>
                    <li><?= esc($error) ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <form method="post" action="<?= site_url('api-keys') ?>" class="mt-5 space-y-5">
            <?= csrf_field() ?>
            <div>
                <label for="name" class="mb-2 block text-sm font-semibold text-slate-200">Nome</label>
                <input id="name" name="name" value="<?= esc(old('name')) ?>" class="block w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-white">
            </div>
            <div>
                <label for="expires_at" class="mb-2 block text-sm font-semibold text-slate-200">Expira em (opcional)</label>
                <input id="expires_at" type="datetime-local" name="expires_at" value="<?= esc(old('expires_at')) ?>" class="block w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-white">
            </div>
            <div>
                <div class="mb-3 text-sm font-semibold text-slate-200">Scopes</div>
                <div id="scopeSelector" class="grid gap-3">
                    <label class="scope-card flex cursor-pointer items-center gap-3 rounded-2xl border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300 transition hover:border-cyan-400/20 hover:bg-white/5 <?= in_array('*', $selectedScopes, true) ? 'is-active border-cyan-400/30 bg-cyan-400/10 text-white' : '' ?>">
                        <input class="scope-input h-4 w-4 accent-cyan-400" type="checkbox" name="scopes[]" value="*" data-scope-all="true" <?= in_array('*', $selectedScopes, true) ? 'checked' : '' ?>>
                        <span>
                            <strong class="block font-semibold">Acesso completo</strong>
                            <span class="block text-xs text-slate-400">Ativa todos os endpoints e ignora a seleção granular.</span>
                        </span>
                    </label>
                    <?php foreach ($availableScopes as $scope): ?>
                        <label class="scope-card flex cursor-pointer items-center gap-3 rounded-2xl border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300 transition hover:border-sky-400/20 hover:bg-white/5 <?= in_array($scope, $selectedScopes, true) ? 'is-active border-sky-400/30 bg-sky-400/10 text-white' : '' ?>">
                            <input class="scope-input h-4 w-4 accent-sky-400" type="checkbox" name="scopes[]" value="<?= esc($scope) ?>" <?= in_array($scope, $selectedScopes, true) ? 'checked' : '' ?>>
                            <span>
                                <strong class="block font-semibold"><?= esc($scope) ?></strong>
                            </span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <button class="inline-flex items-center justify-center rounded-2xl bg-gradient-to-r from-sky-400 to-cyan-400 px-5 py-3 text-sm font-semibold text-slate-950 transition hover:opacity-90" type="submit">Emitir API key</button>
        </form>
    </article>
</section>

<section class="rounded-[30px] border border-white/10 bg-white/5 p-6 backdrop-blur">
    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
        <div>
            <h2 class="text-xl font-semibold text-white">Chaves emitidas</h2>
            <p class="mt-1 text-sm text-slate-400">Lista de tokens ativos ou revogados para o tenant atual.</p>
        </div>
        <div class="rounded-full border border-white/10 bg-slate-950/60 px-4 py-2 text-sm text-slate-300"><?= count($apiKeys) ?> registos</div>
    </div>

    <div class="mt-5 overflow-hidden rounded-3xl border border-white/10">
        <table class="min-w-full divide-y divide-white/10 text-sm">
            <thead class="bg-slate-950/60 text-left text-xs uppercase tracking-[0.24em] text-slate-400">
                <tr>
                    <th class="px-4 py-4">Nome</th>
                    <th class="px-4 py-4">Prefixo</th>
                    <th class="px-4 py-4">Scopes</th>
                    <th class="px-4 py-4">Status</th>
                    <th class="px-4 py-4">Último uso</th>
                    <th class="px-4 py-4">Expira</th>
                    <th class="px-4 py-4">Ações</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-white/5 bg-white/3">
                <?php if ($apiKeys === []): ?>
                    <tr>
                        <td colspan="7" class="px-4 py-6 text-center text-slate-400">Ainda não existem API keys para este tenant.</td>
                    </tr>
                <?php endif; ?>
                <?php foreach ($apiKeys as $apiKey): ?>
                    <tr class="transition hover:bg-white/5">
                        <td class="px-4 py-4 font-medium text-white"><?= esc($apiKey['name']) ?></td>
                        <td class="px-4 py-4 font-mono text-slate-300"><?= esc($apiKey['key_prefix']) ?>...</td>
                        <td class="px-4 py-4 text-slate-300"><?php $displayScopes = array_map(static fn (string $scope): string => $scopeAliases[$scope] ?? $scope, $apiKey['scope_list'] ?? []); ?><?= esc(implode(', ', array_values(array_unique($displayScopes)))) ?></td>
                        <td class="px-4 py-4">
                            <span class="inline-flex rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] <?= ($apiKey['status'] ?? 'active') === 'active' ? 'border-sky-400/20 bg-sky-400/10 text-sky-100' : 'border-rose-400/20 bg-rose-400/10 text-rose-100' ?>">
                                <?= esc($apiKey['status']) ?>
                            </span>
                        </td>
                        <td class="px-4 py-4 text-slate-300"><?= esc($apiKey['last_used_at'] ? date('d/m/Y H:i', strtotime((string) $apiKey['last_used_at'])) : '-') ?></td>
                        <td class="px-4 py-4 text-slate-300"><?= esc($apiKey['expires_at'] ? date('d/m/Y H:i', strtotime((string) $apiKey['expires_at'])) : '-') ?></td>
                        <td class="px-4 py-4">
                            <?php if (($apiKey['status'] ?? 'active') === 'active'): ?>
                                <form method="post" action="<?= site_url('api-keys/' . $apiKey['id'] . '/revoke') ?>" onsubmit="return confirm('Revogar esta API key?');">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="inline-flex items-center justify-center rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/20">Revogar</button>
                                </form>
                            <?php else: ?>
                                <span class="text-slate-500">Sem ações</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>
<script>
    (() => {
        const selector = document.getElementById('scopeSelector');
        if (!selector) {
            return;
        }

        const allInput = selector.querySelector('[data-scope-all="true"]');
        const scopeInputs = Array.from(selector.querySelectorAll('.scope-input:not([data-scope-all="true"])'));
        const cards = Array.from(selector.querySelectorAll('.scope-card'));

        const paint = () => {
            cards.forEach((card) => {
                const input = card.querySelector('.scope-input');
                if (!input) {
                    return;
                }

                card.classList.toggle('is-active', input.checked);

                if (input.checked) {
                    if (input.hasAttribute('data-scope-all')) {
                        card.classList.add('border-cyan-400/30', 'bg-cyan-400/10', 'text-white');
                        card.classList.remove('border-white/10', 'bg-slate-950/40', 'text-slate-300');
                    } else {
                        card.classList.add('border-sky-400/30', 'bg-sky-400/10', 'text-white');
                        card.classList.remove('border-white/10', 'bg-slate-950/40', 'text-slate-300');
                    }
                } else {
                    card.classList.remove('border-cyan-400/30', 'bg-cyan-400/10', 'border-sky-400/30', 'bg-sky-400/10', 'text-white');
                    card.classList.add('border-white/10', 'bg-slate-950/40', 'text-slate-300');
                }
            });
        };

        const syncDisabled = () => {
            const fullAccess = !!(allInput && allInput.checked);
            scopeInputs.forEach((input) => {
                input.disabled = fullAccess;
                input.closest('.scope-card')?.classList.toggle('opacity-60', fullAccess);
            });
        };

        allInput?.addEventListener('change', () => {
            if (allInput.checked) {
                scopeInputs.forEach((input) => {
                    input.checked = false;
                });
            }
            syncDisabled();
            paint();
        });

        scopeInputs.forEach((input) => {
            input.addEventListener('change', () => {
                if (input.checked && allInput) {
                    allInput.checked = false;
                }
                syncDisabled();
                paint();
            });
        });

        syncDisabled();
        paint();
    })();
</script>
<?= $this->endSection() ?>
