import { A, useNavigate } from '@solidjs/router';
import { createResource, createSignal, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

type ExternalRole = {
  id: string;
  roleKey: string;
  displayName: string;
  vertical: string;
  enabledModules: string[];
  onboardingSchemaId: string;
  isActive: boolean;
};

async function loadExternalRoles(): Promise<ExternalRole[]> {
  try {
    const res = await fetch(`${API}/api/admin/roles?audience=EXTERNAL`);
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    const rows = Array.isArray(data) ? data : (data.roles || []);
    return rows.map((r: any) => ({
      id: r.id,
      roleKey: r.key || r.role_key || r.roleKey || '',
      displayName: r.name || r.displayName || r.display_name || r.key || '',
      vertical: r.config_json?.vertical || r.vertical || '',
      enabledModules: r.config_json?.enabledModules || r.enabled_modules || [],
      onboardingSchemaId: r.config_json?.onboardingSchemaId || r.onboarding_schema_id || '',
      isActive: r.is_active !== false,
    }));
  } catch {
    return [];
  }
}

export default function RuntimeRolesPage() {
  const navigate = useNavigate();
  const [roles, { refetch }] = createResource(loadExternalRoles);
  const [deleting, setDeleting] = createSignal('');
  const [deleteError, setDeleteError] = createSignal('');

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Delete external role "${name}"?`)) return;
    try {
      setDeleting(id);
      const res = await fetch(`${API}/api/admin/roles/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete');
      refetch();
    } catch (err: any) {
      setDeleteError(err.message || 'Failed to delete');
    } finally {
      setDeleting('');
    }
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">External Role Management</h1>
          <p class="page-subtitle">Manage canonical external runtime roles, enabled modules, onboarding assignment, and approval gates from one place.</p>
        </div>
        <A class="btn navy" href="/admin/runtime-roles/new">Create External Role</A>
      </div>

      <Show when={deleteError()}>
        <div class="error-box">{deleteError()}</div>
      </Show>

      <section class="card" style="padding: 0; overflow: hidden;">
        <div style="display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid #e2e8f0">
          <div>
            <h2 style="margin:0;font-size:17px;font-weight:700">Published External Roles</h2>
            <p style="margin:4px 0 0;font-size:12px;color:#64748b">Only canonical external runtime roles are shown here.</p>
          </div>
          <Show when={!roles.loading}>
            <span style="font-size:13px;color:#64748b">{roles()?.length || 0} roles</span>
          </Show>
        </div>
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Role</th>
                <th>Type</th>
                <th>Modules</th>
                <th>Schema</th>
                <th>Status</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={roles.loading}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#64748b">Loading external roles...</td></tr>
              </Show>
              <Show when={!roles.loading && roles.error}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#b91c1c">Failed to load external roles. Is the backend running?</td></tr>
              </Show>
              <Show when={!roles.loading && !roles.error && roles()?.length === 0}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#94a3b8">No external roles configured yet.</td></tr>
              </Show>
              <Show when={!roles.loading && !roles.error && (roles()?.length ?? 0) > 0}>
                {roles()!.map((role) => (
                  <tr>
                    <td>
                      <div>
                        <p style="margin:0;font-weight:600;color:#0f172a">{role.displayName}</p>
                        <p style="margin:2px 0 0;font-size:11px;color:#94a3b8">{role.roleKey}</p>
                      </div>
                    </td>
                    <td style="color:#475569">{role.vertical || '—'}</td>
                    <td style="color:#475569">{role.enabledModules.length}</td>
                    <td style="color:#475569;font-size:12px">{role.onboardingSchemaId || '—'}</td>
                    <td>
                      <span class={`status-chip ${role.isActive ? 'active' : ''}`}>
                        {role.isActive ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td>
                      <div class="table-actions">
                        <A class="btn" href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`}>Edit</A>
                        <button
                          class="btn danger"
                          disabled={deleting() === role.id}
                          onClick={() => handleDelete(role.id, role.displayName)}
                        >
                          {deleting() === role.id ? '...' : 'Delete'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
