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

const API = '/api/gateway';

type Role = {
  id: string;
  name: string;
  description?: string;
  code?: string;
};

async function loadInternalRoles(): Promise<Role[]> {
  try {
    const res = await fetch(`${API}/api/admin/roles?audience=INTERNAL`);
    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,
      name: r.name,
      description: r.description || '',
      code: r.code || r.key || '',
    }));
  } catch {
    return [];
  }
}

export default function InternalRolesPage() {
  const [roles, { refetch }] = createResource(loadInternalRoles);
  const [deleting, setDeleting] = createSignal('');
  const [deleteError, setDeleteError] = createSignal('');

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

  return (
    <AdminShell>
      <div class="page-hero-card page-actions">
        <div>
          <h1 class="page-title">Internal Role Management</h1>
          <p class="page-subtitle">Manage internal employee roles and permissions from one clean list.</p>
        </div>
        <A class="btn navy" href="/admin/roles/create">Create Internal Role</A>
      </div>

      <nav class="admin-link-tabs" aria-label="Role Management Navigation">
        <A class="admin-link-tab active" href="/admin/roles">Internal Roles</A>
        <A class="admin-link-tab" href="/admin/runtime-roles">External Runtime Roles</A>
        <A class="admin-link-tab" href="/admin/onboarding-schemas">Onboarding Schemas</A>
      </nav>

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

      <section class="card" style="padding: 0; overflow: hidden;">
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Description</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={roles.loading}>
                <tr>
                  <td colspan="3" style="text-align:center;padding:32px;color:#64748b;">Loading internal roles...</td>
                </tr>
              </Show>
              <Show when={!roles.loading && roles.error}>
                <tr>
                  <td colspan="3" style="text-align:center;padding:32px;color:#b91c1c;">Failed to load roles. Is the backend running?</td>
                </tr>
              </Show>
              <Show when={!roles.loading && !roles.error && roles()?.length === 0}>
                <tr>
                  <td colspan="3" style="text-align:center;padding:32px;color:#94a3b8;">No internal roles found. Create your first role.</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.name}</p>
                        <p style="margin:2px 0 0;font-size:11px;color:#94a3b8;">{role.code || role.id?.slice(0, 8)}</p>
                      </div>
                    </td>
                    <td style="color:#475569;">{role.description || 'No description added yet.'}</td>
                    <td>
                      <div class="table-actions">
                        <A class="action-icon-btn" href={`/admin/roles/${role.id}`} title="View Role">👁</A>
                        <A class="action-icon-btn" href={`/admin/roles/${role.id}/edit`} title="Edit Role">✎</A>
                        <button
                          class="action-icon-btn danger"
                          disabled={deleting() === role.id}
                          onClick={() => handleDelete(role.id, role.name)}
                          title="Delete Role"
                        >
                          {deleting() === role.id ? '...' : '🗑'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
