import { A } from '@solidjs/router';
import { createResource, Show } 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, { refetch }] = createResource(() => listRuntimeConfigs<RuntimeRoleConfig>('role'));

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

  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>
        <Show when={items.loading}>
            <p class="notice">Loading roles from database...</p>
        </Show>
        <Show when={!items.loading && items() && items()?.length === 0}>
          <p class="notice">No runtime role configs found yet.</p>
        </Show>
        <Show when={!items.loading && items() && items()!.length > 0}>
            <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).toLocaleDateString()}</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>
        </Show>
      </section>
    </AdminShell>
  );
}
