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">External Role Management</h1>
      <p class="page-subtitle">Manage canonical external runtime roles from one place.</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="table-wrap">
            <table class="list-table">
              <thead>
                <tr>
                  <th>Role</th>
                  <th>Status</th>
                  <th>Updated</th>
                  <th class="align-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {items()!.map((item) => (
                  <tr>
                    <td>{item.key}</td>
                    <td><span class={`status-chip ${item.status === 'published' ? 'active' : ''}`}>{item.status}</span></td>
                    <td>{new Date(item.updatedAt).toLocaleDateString()}</td>
                    <td>
                      <div class="table-actions">
                        <A class="btn" href={`/admin/runtime-roles/${encodeURIComponent(item.key)}`}>Edit</A>
                        <button class="btn" onClick={() => onDelete(item.key)}>Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Show>
      </section>
    </AdminShell>
  );
}
