import { A, useSearchParams } from '@solidjs/router';
import { createMemo, createResource, 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 || []))
      .filter((item: any) => String(item?.audience || '').toUpperCase() === 'EXTERNAL');
    return await Promise.all(
      rows.map(async (r: any) => {
        const roleId = String(r.id || '');
        const roleKey = String(r.key || r.role_key || r.roleKey || '');
        const cfg = r.config_json || {};

        let enabledModules = Array.isArray(cfg?.enabledModules) ? cfg.enabledModules : [];
        let onboardingSchemaId = String(cfg?.onboardingSchemaId || r.onboarding_schema_id || '');

        if (roleId) {
          try {
            const dashboardRes = await fetch(`${API}/api/admin/dashboard-config/${roleId}?audience=EXTERNAL`);
            if (dashboardRes.ok) {
              const detail = await dashboardRes.json();
              const json = detail?.config_json || {};
              const byEnabled = Array.isArray(json?.enabled_modules) ? json.enabled_modules : [];
              const byNav = Array.isArray(json?.nav) ? json.nav.map((item: any) => String(item?.key || '').trim()).filter(Boolean) : [];
              if (enabledModules.length === 0) {
                enabledModules = byEnabled.length > 0 ? byEnabled : byNav;
              }
            }
          } catch {}

          try {
            const onboardingRes = await fetch(`${API}/api/admin/onboarding-config/${roleId}`);
            if (onboardingRes.ok) {
              const onboarding = await onboardingRes.json();
              if (!onboardingSchemaId) onboardingSchemaId = String(onboarding?.id || '');
            }
          } catch {}
        }

        return {
          id: roleId,
          roleKey,
          displayName: r.name || r.displayName || r.display_name || roleKey,
          vertical: cfg?.vertical || r.vertical || '',
          enabledModules,
          onboardingSchemaId,
          isActive: r.is_active !== false,
        };
      }),
    );
  } catch {
    return [];
  }
}

export default function RuntimeRolesPage() {
  const [searchParams] = useSearchParams();
  const [roles] = createResource(loadExternalRoles);
  const selectedRoleKey = createMemo(() => (searchParams.roleKey || '').toLowerCase());

  return (
    <AdminShell>
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <h1 class="text-xl font-semibold text-gray-900">External Role Management</h1>
          <p class="text-sm text-gray-500 mt-0.5">Configure and maintain external system roles and access privileges.</p>
        </div>

        <div class="flex-1 p-6">
          <div class="table-card">
            <div class="overflow-x-auto">
              <table data-table class="w-full min-w-[860px] text-sm">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Issue Type</th>
                    <th class="text-center">Edit</th>
                    <th class="text-center">Delete</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={roles.loading}>
                    <tr><td colspan="5" class="text-center px-8 py-8 text-slate-500">Loading external roles...</td></tr>
                  </Show>
                  <Show when={!roles.loading && roles.error}>
                    <tr><td colspan="5" class="text-center px-8 py-8 text-red-600">Failed to load external roles. Is the backend running?</td></tr>
                  </Show>
                  <Show when={!roles.loading && !roles.error && roles()?.length === 0}>
                    <tr><td colspan="5" class="text-center px-8 py-8 text-slate-400">No external roles configured yet.</td></tr>
                  </Show>
                  <Show when={!roles.loading && !roles.error && (roles()?.length ?? 0) > 0}>
                    {roles()!.map((role) => (
                      <tr class={`hover:bg-slate-50 ${selectedRoleKey() === role.roleKey.toLowerCase() ? 'bg-slate-50' : ''}`}>
                        <td class="text-slate-500">{role.roleKey || role.id?.slice(0, 6).toUpperCase()}</td>
                        <td class="font-semibold text-slate-900">{role.displayName}</td>
                        <td class="text-slate-500">
                          <A class="inline-flex items-center gap-1 font-medium text-[#0a1d37] hover:text-[#0f2a4e]" href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`} target="_blank" rel="noreferrer">
                            <span>View</span>
                            <span>↗</span>
                          </A>
                        </td>
                        <td class="text-center">
                          <A class="inline-flex h-8 w-8 items-center justify-center rounded-md text-slate-600 hover:bg-slate-100" href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`} title="Edit External Role">✎</A>
                        </td>
                        <td class="text-center">
                          <button class="inline-flex h-8 w-8 items-center justify-center rounded-md text-red-600 hover:bg-red-50" title="Delete External Role" aria-label={`Delete ${role.displayName}`}>🗑</button>
                        </td>
                      </tr>
                    ))}
                  </Show>
                </tbody>
              </table>
            </div>
            <div class="flex items-center justify-between border-t border-gray-200 px-6 py-4">
              <p class="text-sm text-slate-500">Showing 1 to 5 of {(roles()?.length || 0) || 5} entries</p>
              <div class="flex items-center gap-2">
                <button class="h-9 min-w-9 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 hover:bg-gray-50">{'<'}</button>
                <button class="h-9 min-w-9 rounded-lg bg-[#0a1d37] px-3 text-sm font-medium text-white">1</button>
                <button class="h-9 min-w-9 rounded-lg border border-gray-200 bg-white px-3 text-sm font-medium text-gray-700 hover:bg-gray-50">2</button>
                <button class="h-9 min-w-9 rounded-lg border border-gray-200 bg-white px-3 text-sm font-medium text-gray-700 hover:bg-gray-50">3</button>
                <button class="h-9 min-w-9 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 hover:bg-gray-50">{'>'}</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </AdminShell>
  );
}
