import { A } from '@solidjs/router';
import { createSignal, onMount } from 'solid-js';
import AdminShell from '~/components/AdminShell';
import { deleteRuntimeConfig, listRuntimeConfigs, type RuntimeListItem } from '~/lib/runtime/storage';
import type { RuntimeRoleConfig } from '~/lib/runtime/types';

export default function ManageRolesPage() {
  const [items, setItems] = createSignal<Array<RuntimeListItem<RuntimeRoleConfig>>>([]);

  const load = () => setItems(listRuntimeConfigs<RuntimeRoleConfig>('role'));

  onMount(load);

  const onDelete = (key: string) => {
    deleteRuntimeConfig('role', key);
    load();
  };

  return (
    <AdminShell>
      <h1 class="page-title">Manage Roles</h1>
      <p class="page-subtitle">Edit or remove runtime role configs saved from the builder.</p>
      <section class="card">
        <div class="list-header">
          <h2>Runtime Roles</h2>
          <A class="btn primary" href="/admin/runtime-roles/new">Create Role</A>
        </div>
        {items().length === 0 ? (
          <p class="notice">No runtime role configs found yet.</p>
        ) : (
          <div class="list-grid">
            {items().map((item) => (
              <article class="list-item">
                <h3>{item.key}</h3>
                <p>Status: <strong>{item.status}</strong></p>
                <p>Updated: {new Date(item.updatedAt).toLocaleString()}</p>
                <div class="actions">
                  <A class="btn" href={`/admin/runtime-roles/${encodeURIComponent(item.key)}`}>Edit</A>
                  <button class="btn" onClick={() => onDelete(item.key)}>Delete</button>
                </div>
              </article>
            ))}
          </div>
        )}
      </section>
    </AdminShell>
  );
}
