import { revalidatePath } from 'next/cache';
import { notFound, redirect } from 'next/navigation';
import { AdminShell, EmptyState, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { appendAudit, deleteAgentMemory, getAgent, getAgentMemory, listAgentToolPermissions, listArtifacts, listAudit, listRuns, listSchedules, updateAgent, updateAgentToolset, upsertSchedule } from '@/lib/runtime.js';
import { listMarketplaceTools } from '@/lib/tools/registry.js';
import { listApprovalRequests } from '@/lib/approvals.js';
import { listSpaces } from '@/lib/dashboard-spaces.js';
import { listAgentEngines } from '@/lib/agent-engines.js';
import { defaultAgentSkillsTemplate, readAgentSkills, writeAgentSkills } from '@/lib/agent-skills.js';
import { getReports, listAgentRuns, listTasks } from '@/lib/delegation.js';
import { listInstancesForAgent } from '@/lib/connection-instances.js';
import { listConnections } from '@/lib/connections.js';
import EngineModelPicker from '../engine-model-picker.jsx';
import { AgentDetailSimple } from './agent-detail-simple';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function safeAgent(id) {
  const agent = getAgent(String(id || ''));
  if (!agent) notFound();
  return agent;
}

function parseMeta(row) {
  try { return row?.meta ? JSON.parse(row.meta) : {}; } catch { return {}; }
}

function agentAuditEvents(agentId) {
  return listAudit(100).filter(row => parseMeta(row).agent_id === agentId || row.summary?.includes(agentId));
}

function agentRuns(agentId) {
  return listRuns(100).filter(run => run.agent_id === agentId || run.agent === agentId);
}

function agentArtifacts(agentId) {
  return listArtifacts(100).filter(artifact => artifact.agent_id === agentId);
}

function AgentConnectionsList({ agentId }) {
  const instances = listInstancesForAgent(agentId);
  const connections = listConnections();
  const titleBySlug = {};
  for (const c of connections) titleBySlug[c.slug] = c.title;

  if (instances.length === 0) {
    return (
      <EmptyState title="No agent-scoped credentials">
        <p>Add a connection just for this agent — useful when you want one GitHub token here but a different one elsewhere.</p>
        <p style={{ marginTop: 8 }}>
          <a className="admin-link" href={`/marketplace?kind=connection&prefill_scope=agent&prefill_agent_id=${encodeURIComponent(agentId)}`}>
            Connect a service for this agent →
          </a>
        </p>
      </EmptyState>
    );
  }

  return (
    <>
      <ul className="agent-detail-connections">
        {instances.map(inst => (
          <li key={inst.id}>
            <a
              className="agent-detail-connection-row"
              href={`/marketplace?kind=connection&connection=${encodeURIComponent(inst.service_key)}`}
            >
              <span className="agent-detail-connection-title">{titleBySlug[inst.service_key] || inst.service_key}</span>
              {inst.account_label ? <span className="agent-detail-connection-meta">{inst.account_label}</span> : null}
              {inst.last_4 ? <span className="agent-detail-connection-meta">••• {inst.last_4}</span> : null}
            </a>
          </li>
        ))}
      </ul>
      <p style={{ marginTop: 10 }}>
        <a className="admin-link" href={`/marketplace?kind=connection&prefill_scope=agent&prefill_agent_id=${encodeURIComponent(agentId)}`}>
          Connect another service for this agent →
        </a>
      </p>
    </>
  );
}

function selectedIndexes(formData, memoryLength = Infinity) {
  return [...new Set(formData.getAll('memory_index')
    .map(value => Number(value))
    .filter(value => Number.isInteger(value) && value >= 0 && value < memoryLength))]
    .sort((a, b) => b - a);
}

async function saveAgentDetailSkillsAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const content = String(formData.get('skills') || '');
  const previous = readAgentSkills(agent.id);
  const saved = writeAgentSkills(agent.id, content);
  appendAudit({
    type: 'agent.skills.update',
    summary: `Updated skills for ${agent.id}`,
    status: 'complete',
    meta: { agent_id: agent.id, previous_bytes: Buffer.byteLength(previous), bytes: Buffer.byteLength(saved), surface: 'agent-detail' },
  });
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

async function resetAgentSkillsAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const previous = readAgentSkills(agent.id);
  const saved = writeAgentSkills(agent.id, defaultAgentSkillsTemplate(agent));
  appendAudit({
    type: 'agent.skills.reset',
    summary: `Reset skills to default for ${agent.id}`,
    status: 'complete',
    meta: { agent_id: agent.id, previous_bytes: Buffer.byteLength(previous), bytes: Buffer.byteLength(saved), surface: 'agent-detail' },
  });
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

async function createAgentSkillsTemplateAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const current = readAgentSkills(agent.id).trim();
  const next = `${current ? `${current}\n\n---\n\n` : ''}${defaultAgentSkillsTemplate(agent)}`;
  const saved = writeAgentSkills(agent.id, next);
  appendAudit({
    type: 'agent.skills.template',
    summary: `Created skills template for ${agent.id}`,
    status: 'complete',
    meta: { agent_id: agent.id, bytes: Buffer.byteLength(saved), surface: 'agent-detail' },
  });
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

async function pruneAgentDetailMemoryAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const indexes = selectedIndexes(formData, getAgentMemory(agent.id)?.length || 0);
  let removed = 0;
  for (const index of indexes) {
    const result = deleteAgentMemory(agent.id, index);
    if (result.ok) removed += 1;
  }
  if (removed) {
    appendAudit({
      type: 'agent.memory.bulk-prune',
      summary: `Bulk prune memory for ${agent.id}`,
      status: 'complete',
      meta: { agent_id: agent.id, removed, surface: 'agent-detail' },
    });
  }
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

async function updateAgentDetailEngineAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const engine = String(formData.get('engine') || '');
  const model = String(formData.get('model') || '').trim();
  if (engine) updateAgent(agent.id, { engine, model: model || undefined });
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

async function saveAgentDetailContractAction(formData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const agent = agentId ? getAgent(agentId) : null;
  if (!agent) redirect('/agents');
  const system_prompt = String(formData.get('system_prompt') || '');
  const expected_output = String(formData.get('expected_output') || '');
  updateAgent(agent.id, { system_prompt, expected_output });
  appendAudit({
    type: 'agent.contract.update',
    summary: `Updated instruction + expected output for ${agent.id}`,
    status: 'complete',
    meta: {
      agent_id: agent.id,
      instruction_bytes: Buffer.byteLength(system_prompt),
      expected_output_bytes: Buffer.byteLength(expected_output),
      surface: 'agent-detail',
    },
  });
  revalidatePath('/agents');
  revalidatePath(`/agents/${agent.id}`);
  redirect(`/agents/${agent.id}?view=details`);
}

export default async function AgentDetailPage({ params, searchParams }) {
  const { id } = await params;
  const query = await searchParams;
  const agent = safeAgent(id);
  const view = query?.view === 'details' ? 'details' : 'simple';
  const engines = await listAgentEngines();
  const schedules = listSchedules().filter(schedule => schedule.agent_id === agent.id);
  const scheduleRaw = schedules[0]?.schedule || agent.schedule || 'on demand';
  const runs = agentRuns(agent.id);

  const headerActions = (
    <a className="admin-button secondary" href="/agents">Back to agents</a>
  );

  if (view === 'simple') {
    const description = agent.mission || 'Open Configuration to set skills, memory, permissions, and engine.';
    const { spaces } = listSpaces();

    // The full tool catalogue, slimmed to what the picker needs. The registry
    // already carries each tool's category, so icons resolve without regex.
    const registryTools = listMarketplaceTools();
    const availableTools = registryTools.map(tool => ({
      name: tool.name,
      title: tool.title || tool.name,
      description: tool.description || '',
      category: tool.category || 'core',
      risk_level: tool.risk_level || 'medium',
      available: tool.available !== false,
      missing_env: tool.missing_env || [],
    }));
    const categoryByTool = new Map(availableTools.map(t => [t.name, t.category]));
    const agentTools = Array.isArray(agent.tools) ? agent.tools : [];

    // One searchable feed: executions (runs) + the approvals this agent raised.
    const executionItems = runs.map(run => ({
      id: `run-${run.id}`,
      kind: 'execution',
      status: run.status || '',
      title: run.title || run.kind || 'Run',
      at: run.at || null,
    }));
    const approvalItems = listApprovalRequests({ limit: 200 })
      .filter(req => req.payload?.agent_id === agent.id
        || req.requested_by === agent.id
        || String(req.summary || '').includes(agent.id))
      .map(req => ({
        id: `approval-${req.id}`,
        kind: 'approval',
        status: req.status || '',
        title: req.summary || req.action_type || 'Approval',
        risk: req.risk || null,
        at: req.decided_at || req.created_at || null,
      }));
    const activity = [...executionItems, ...approvalItems]
      .sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')))
      .slice(0, 40);

    async function updateDefaultSpaceAction(formData) {
      'use server';
      const agentId = String(formData.get('agent_id') || '');
      const raw = String(formData.get('default_space_id') || '');
      const next = raw === '' ? null : raw;
      if (!agentId) return;
      updateAgent(agentId, { default_space_id: next });
      revalidatePath(`/agents/${agentId}`);
      redirect(`/agents/${agentId}`);
    }

    async function updateModelSimpleAction(formData) {
      'use server';
      const agentId = String(formData.get('agent_id') || '');
      const a = agentId ? getAgent(agentId) : null;
      if (!a) redirect('/agents');
      const engine = String(formData.get('engine') || '');
      const model = String(formData.get('model') || '').trim();
      if (engine) updateAgent(a.id, { engine, model: model || undefined });
      revalidatePath('/agents');
      revalidatePath(`/agents/${a.id}`);
      redirect(`/agents/${a.id}`);
    }

    async function updateScheduleSimpleAction(formData) {
      'use server';
      const agentId = String(formData.get('agent_id') || '');
      const a = agentId ? getAgent(agentId) : null;
      if (!a) redirect('/agents');
      const schedule = String(formData.get('schedule') || 'on demand').trim() || 'on demand';
      upsertSchedule({ agent_id: a.id, name: a.name, schedule, action_kind: 'agent-tick' });
      updateAgent(a.id, { schedule });
      revalidatePath('/agents');
      revalidatePath('/schedules');
      revalidatePath(`/agents/${a.id}`);
      redirect(`/agents/${a.id}`);
    }

    async function updateToolsSimpleAction(formData) {
      'use server';
      const agentId = String(formData.get('agent_id') || '');
      const a = agentId ? getAgent(agentId) : null;
      if (!a) redirect('/agents');
      const tools = formData.getAll('tool').map(t => String(t || '').trim()).filter(Boolean);
      updateAgentToolset(a.id, tools);
      revalidatePath('/agents');
      revalidatePath(`/agents/${a.id}`);
      redirect(`/agents/${a.id}`);
    }

    return (
      <AdminShell
        kicker="Agent"
        title={agent.name}
        description={description}
        actions={headerActions}
        hideProjectSwitcher
      >
        <div className="mkt-page" data-page="agent-detail" data-view="simple">
          <AgentDetailSimple
            agent={agent}
            scheduleRaw={scheduleRaw}
            recentRuns={runs}
            activity={activity}
            spaces={spaces}
            engines={engines}
            agentTools={agentTools}
            availableTools={availableTools}
            toolCategories={[...new Set(agentTools.map(t => categoryByTool.get(t)).filter(Boolean))]}
            updateDefaultSpaceAction={updateDefaultSpaceAction}
            updateModelAction={updateModelSimpleAction}
            updateScheduleAction={updateScheduleSimpleAction}
            updateToolsAction={updateToolsSimpleAction}
          />
        </div>
      </AdminShell>
    );
  }

  // Details mode — full debug surface.
  const permissions = listAgentToolPermissions(agent.id);
  const skills = readAgentSkills(agent.id);
  const memory = getAgentMemory(agent.id) || [];
  const memorySearch = String(query?.memory || '').trim().toLowerCase();
  const filteredMemory = memory
    .map((entry, index) => ({ entry, index }))
    .filter(item => !memorySearch || String(item.entry).toLowerCase().includes(memorySearch));
  const audits = agentAuditEvents(agent.id);
  const artifacts = agentArtifacts(agent.id);
  const activeTasks = listTasks({ assignee_agent_id: agent.id, limit: 100 }).filter(task => ['todo', 'in_progress', 'in_review', 'blocked'].includes(task.status));
  const currentRun = listAgentRuns({ agent_id: agent.id, limit: 20 }).find(run => ['queued', 'running', 'waiting_approval'].includes(run.status));
  const reports = getReports(agent.id);
  const lastKnowledgeAudit = audits.find(row => ['agent.skills.update', 'agent.skills.reset', 'agent.skills.template', 'agent.memory.delete', 'agent.memory.bulk-prune'].includes(row.type));
  const engineLabel = engines.find(e => e.id === agent.engine)?.label || agent.engine;
  const scheduleSummary = schedules[0]?.schedule || agent.schedule || 'on demand';
  const statusTone = agent.status === 'heartbeat ok' ? 'ready' : 'neutral';

  const detailsHeaderActions = (
    <>
      <StatusPill tone={statusTone}>{agent.status || 'created'}</StatusPill>
      <a className="admin-button secondary" href={`/agents/${agent.id}`}>Back to agent</a>
    </>
  );

  return (
    <AdminShell
      kicker="Agent Knowledge Detail"
      title={agent.name}
      description={agent.mission
        ? `Knowledge operations · ${agent.mission}`
        : 'Knowledge operations, memory search, audit history, tool permissions, and runs history for one worker.'}
      actions={detailsHeaderActions}
    >
      <div className="mkt-page" data-page="agent-detail" data-view="details">
        {/* Compact overview — the operative numbers, calm not debug-dumpy */}
        <section className="ad-overview">
          <div className="ad-overview-card">
            <span className="ad-overview-label">Engine</span>
            <span className="ad-overview-value">{engineLabel}{agent.model ? ` · ${agent.model}` : ''}</span>
          </div>
          <div className="ad-overview-card">
            <span className="ad-overview-label">Schedule</span>
            <span className="ad-overview-value">{scheduleSummary}</span>
          </div>
          <div className="ad-overview-card">
            <span className="ad-overview-label">Memory</span>
            <span className="ad-overview-value">{memory.length} {memory.length === 1 ? 'entry' : 'entries'}</span>
          </div>
          <div className="ad-overview-card">
            <span className="ad-overview-label">Runs</span>
            <span className="ad-overview-value">{runs.length}</span>
          </div>
          <div className="ad-overview-card">
            <span className="ad-overview-label">Active tasks</span>
            <span className="ad-overview-value">{activeTasks.length}</span>
          </div>
          <div className="ad-overview-card">
            <span className="ad-overview-label">Audit events</span>
            <span className="ad-overview-value">{audits.length}</span>
          </div>
        </section>

        <section className="admin-panel ad-panel agent-detail-summary">
          <div className="admin-panel-head">
            <span>Identity &amp; engine</span>
            <small>Stable ID, budget, delegation, and which model runs this agent.</small>
          </div>
          <div className="ad-kv-grid">
            <div className="ad-kv"><span>Agent ID</span><b className="agent-detail-id">{agent.id}</b></div>
            <div className="ad-kv"><span>Autonomy</span><b>{agent.autonomy_mode || 'managed'}</b></div>
            <div className="ad-kv"><span>Budget</span><b>{agent.spent_monthly_cents || 0} / {agent.budget_monthly_cents || 0} cents</b></div>
            <div className="ad-kv"><span>Current run</span><b>{currentRun?.status || 'idle'}</b></div>
            <div className="ad-kv"><span>Direct reports</span><b>{reports.length}</b></div>
            <div className="ad-kv"><span>Next run</span><b>{schedules[0]?.next_run_at || '—'}</b></div>
          </div>
          {agent.status_reason ? <p className="ad-status-reason">{agent.status_reason}</p> : null}
          <details className="agent-detail-engine-edit">
            <summary className="admin-button secondary">Change engine</summary>
            <form action={updateAgentDetailEngineAction} className="agent-engine-form">
              <input type="hidden" name="agent_id" value={agent.id} />
              <EngineModelPicker engines={engines} initialEngine={agent.engine} initialModel={agent.model || ''} />
              <button className="admin-button" type="submit">Save engine</button>
            </form>
          </details>
        </section>

        <section className="admin-panel ad-panel agent-detail-contract">
          <div className="admin-panel-head">
            <span>Instruction &amp; expected output</span>
            <small>The agent&apos;s standing contract — overridable per task or per run</small>
          </div>
          <form action={saveAgentDetailContractAction} className="agent-contract-form">
            <input type="hidden" name="agent_id" value={agent.id} />
            <label className="agent-contract-field">
              <span>Instruction (system prompt)</span>
              <small>What this agent does and how. Used as the base prompt every run. Leave blank to regenerate the default.</small>
              <textarea name="system_prompt" rows={10} defaultValue={agent.system_prompt || ''} aria-label={`${agent.name} instruction editor`} />
            </label>
            <label className="agent-contract-field">
              <span>Expected output</span>
              <small>What a complete, correct deliverable must contain — format, required sections, acceptance criteria. A delegated task&apos;s acceptance_criteria or a per-call override takes precedence for that run.</small>
              <textarea name="expected_output" rows={6} defaultValue={agent.expected_output || ''} aria-label={`${agent.name} expected output editor`} placeholder="e.g. A markdown report with: (1) Summary, (2) Key findings with sources, (3) Recommended actions. No status recaps." />
            </label>
            <div className="agent-detail-actions">
              <button className="admin-button" type="submit">Save contract</button>
            </div>
          </form>
        </section>

        <div className="agent-detail-layout">
          <section className="admin-panel ad-panel agent-detail-skills">
            <div className="admin-panel-head">
              <span>Skills editor</span>
              <small>Last edited: {lastKnowledgeAudit?.at || 'No knowledge changes yet'}</small>
            </div>
            <form action={saveAgentDetailSkillsAction} className="agent-skills-form">
              <input type="hidden" name="agent_id" value={agent.id} />
              <textarea name="skills" rows={14} defaultValue={skills} aria-label={`${agent.name} full skills editor`} />
              <div className="agent-detail-actions">
                <button className="admin-button" type="submit">Save skills</button>
                <span style={{ flex: 1 }} />
                <button form="agent-template-form" className="admin-button secondary" type="submit">Create from template</button>
                <button form="agent-reset-form" className="admin-button danger" type="submit">Reset skills to default</button>
              </div>
            </form>
            <form id="agent-template-form" action={createAgentSkillsTemplateAction} style={{ display: 'none' }}>
              <input type="hidden" name="agent_id" value={agent.id} />
            </form>
            <form id="agent-reset-form" action={resetAgentSkillsAction} style={{ display: 'none' }}>
              <input type="hidden" name="agent_id" value={agent.id} />
            </form>
          </section>

          <aside className="agent-detail-side">
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Tool permissions</span>
                <small>{permissions.length ? `${permissions.length} override${permissions.length === 1 ? '' : 's'}` : 'default approval-required'}</small>
              </div>
              {permissions.length ? (
                <ul className="agent-detail-perm-list">
                  {permissions.map(permission => (
                    <li key={permission.id}>
                      <span className="agent-detail-perm-name">{permission.tool_name}</span>
                      <StatusPill>{permission.mode}</StatusPill>
                    </li>
                  ))}
                </ul>
              ) : <EmptyState title="Default approval-required">No per-tool override recorded.</EmptyState>}
            </section>

            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Connections</span>
                <small>Credentials bound directly to this agent. Global secrets are inherited automatically.</small>
              </div>
              <AgentConnectionsList agentId={agent.id} />
            </section>

            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Memory pruning</span>
                <small>Search, select, bulk prune. {memory.length} total.</small>
              </div>
              <form className="agent-memory-search" action={`/agents/${agent.id}`}>
                <input type="hidden" name="view" value="details" />
                <label>Memory search<input name="memory" defaultValue={memorySearch} placeholder="filter durable learnings" /></label>
                <button className="admin-button secondary" type="submit">Search memory</button>
                {memorySearch ? <a className="admin-button secondary" href={`/agents/${agent.id}?view=details`}>Clear</a> : null}
              </form>
              {filteredMemory.length ? (
                <form action={pruneAgentDetailMemoryAction} className="agent-memory-bulk-form">
                  <input type="hidden" name="agent_id" value={agent.id} />
                  <div className="agent-memory-bulk-list">
                    {filteredMemory.map(item => (
                      <label key={`${agent.id}-${item.index}`} className="agent-memory-select-row">
                        <input type="checkbox" name="memory_index" value={item.index} />
                        <span><b>#{item.index + 1}</b>{item.entry}</span>
                      </label>
                    ))}
                  </div>
                  <div className="agent-detail-actions">
                    <button className="admin-button danger" type="submit">Bulk prune selected memory</button>
                  </div>
                </form>
              ) : <EmptyState title="No matching memory">No memory entries matched the current search.</EmptyState>}
              <details className="agent-memory-export">
                <summary>Memory export</summary>
                <pre>{JSON.stringify(memory, null, 2)}</pre>
              </details>
            </section>

            <section className="admin-panel">
              <div className="admin-panel-head"><span>Runs history</span><small>{runs.length} total · showing 8</small></div>
              {runs.length ? (
                <div className="admin-table-wrap">
                  <table className="admin-table">
                    <thead><tr><th>When</th><th>Kind</th><th>Status</th></tr></thead>
                    <tbody>
                      {runs.slice(0, 8).map(run => <tr key={run.id}><td>{run.at?.slice(0, 16) || '—'}</td><td>{run.kind}</td><td>{run.status}</td></tr>)}
                    </tbody>
                  </table>
                </div>
              ) : <EmptyState title="No runs yet">Manual or scheduled runs will appear here.</EmptyState>}
            </section>

            <section className="admin-panel">
              <div className="admin-panel-head"><span>Audit history</span><small>{audits.length} events · showing 8</small></div>
              {audits.length ? (
                <ul className="agent-detail-audit-list">
                  {audits.slice(0, 8).map(row => (
                    <li key={row.id}>
                      <div><b>{row.type}</b><StatusPill>{row.status || 'logged'}</StatusPill></div>
                      <p>{row.summary}</p>
                      <small>{row.at}</small>
                    </li>
                  ))}
                </ul>
              ) : <EmptyState title="No audit events">Knowledge updates and memory pruning will appear here.</EmptyState>}
            </section>

            {artifacts.length ? (
              <section className="admin-panel">
                <div className="admin-panel-head"><span>Recent artifacts</span><small>{artifacts.length} total · showing 6</small></div>
                <div className="agent-detail-artifact-grid">
                  {artifacts.slice(0, 6).map(artifact => (
                    <a className="admin-mini-card link" href={`/reports/${encodeURIComponent(artifact.path)}`} key={artifact.id}>
                      <b>{artifact.title || artifact.kind || artifact.id}</b>
                      <p>{artifact.path}</p>
                    </a>
                  ))}
                </div>
              </section>
            ) : null}
          </aside>
        </div>
      </div>
    </AdminShell>
  );
}
