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="mb-8">
        <h1 class="text-[52px] font-extrabold tracking-tight text-[#071b3d] sm:text-[36px] lg:text-[52px]">Roles Management</h1>
        <p class="mt-2 text-[17px] text-[#4b5563]">Configure and maintain external system roles and access privileges.</p>
      </div>

      <section class="overflow-hidden rounded-[22px] border border-[#d8dbe5] bg-white shadow-[0_14px_28px_-20px_rgba(15,23,42,0.35)]">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[860px] text-sm">
            <thead>
              <tr class="bg-[#071b3d] text-white">
                <th class="px-8 py-5 text-left text-[14px] font-semibold uppercase tracking-[0.08em]">ID</th>
                <th class="px-8 py-5 text-left text-[14px] font-semibold uppercase tracking-[0.08em]">Name</th>
                <th class="px-8 py-5 text-left text-[14px] font-semibold uppercase tracking-[0.08em]">Issue Type</th>
                <th class="px-8 py-5 text-center text-[14px] font-semibold uppercase tracking-[0.08em]">Edit</th>
                <th class="px-8 py-5 text-center text-[14px] font-semibold uppercase tracking-[0.08em]">Delete</th>
              </tr>
            </thead>
            <tbody>
              <Show when={roles.loading}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#64748b">Loading external roles...</td></tr>
              </Show>
              <Show when={!roles.loading && roles.error}>
                <tr><td colspan="5" 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="5" 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 class={`border-b border-[#e4e7ef] text-[17px] ${selectedRoleKey() === role.roleKey.toLowerCase() ? 'bg-[#fff7f2]' : ''}`}>
                    <td class="px-8 py-7 font-medium text-[#364152]">{role.roleKey || role.id?.slice(0, 6).toUpperCase()}</td>
                    <td class="px-8 py-7 font-semibold text-[#0f172a]">{role.displayName}</td>
                    <td class="px-8 py-7">
                      <A class="inline-flex items-center gap-2 font-semibold text-[#fd6216] hover:text-orange-700" href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`} target="_blank" rel="noreferrer">
                        <span>View</span>
                        <span class="text-[18px]">↗</span>
                      </A>
                    </td>
                    <td class="px-8 py-7 text-center">
                      <A class="inline-flex h-9 w-9 items-center justify-center rounded-md text-[#071b3d] hover:bg-slate-100" href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`} title="Edit External Role">✎</A>
                    </td>
                    <td class="px-8 py-7 text-center">
                      <button class="inline-flex h-9 w-9 items-center justify-center rounded-md text-[#c81e1e] 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-[#e4e7ef] px-8 py-5">
          <p class="text-[14px] font-semibold uppercase tracking-[0.1em] text-[#485163]">Showing 1 to 5 of {(roles()?.length || 0) || 5} entries</p>
          <div class="flex items-center gap-2">
            <button class="h-11 min-w-11 rounded-xl border border-[#d4d8e2] bg-white px-3 text-[#111827]">{'<'}</button>
            <button class="h-11 min-w-11 rounded-xl bg-[#fd6216] px-3 font-bold text-white">1</button>
            <button class="h-11 min-w-11 rounded-xl border border-[#d4d8e2] bg-white px-3 font-bold text-[#111827]">2</button>
            <button class="h-11 min-w-11 rounded-xl border border-[#d4d8e2] bg-white px-3 font-bold text-[#111827]">3</button>
            <button class="h-11 min-w-11 rounded-xl border border-[#d4d8e2] bg-white px-3 text-[#111827]">{'>'}</button>
          </div>
        </div>
      </section>
    </AdminShell>
  );
}
