import { A, useNavigate, useSearchParams } from '@solidjs/router';
import { For, createMemo, createResource, Show } from 'solid-js';
import ExternalRoleTabs from '~/components/admin/ExternalRoleTabs';

const API = '';

type ExternalRole = {
  id: string;
  roleKey: string;
  displayName: string;
  vertical: string;
  roleCategory: string;
  onboardingSchemaId: string;
  runtimeConfigVersion: number;
  enabledModules: string[];
  permissions: Record<string, string[]>;
  featureLimits: Record<string, unknown>;
  requiresOnboardingApproval: boolean;
  requiresLeadApproval: boolean;
  requiresJobApproval: boolean;
  isActive: boolean;
};

function parseRole(item: any): ExternalRole {
  const cfg = item.config_json || {};
  return {
    id: String(item.id || ''),
    roleKey: String(cfg.roleKey || item.key || item.role_key || ''),
    displayName: String(cfg.displayName || item.name || ''),
    vertical: String(cfg.vertical || ''),
    roleCategory: String(cfg.roleCategory || ''),
    onboardingSchemaId: String(cfg.onboardingSchemaId || ''),
    runtimeConfigVersion: Number(cfg.version || cfg.runtimeConfigVersion || 1),
    enabledModules: Array.isArray(cfg.enabledModules) ? cfg.enabledModules : [],
    permissions: (cfg.permissions && typeof cfg.permissions === 'object') ? cfg.permissions : {},
    featureLimits: (cfg.featureLimits && typeof cfg.featureLimits === 'object') ? cfg.featureLimits : {},
    requiresOnboardingApproval: cfg.requiresOnboardingApproval ?? false,
    requiresLeadApproval: cfg.requiresLeadApproval ?? false,
    requiresJobApproval: cfg.requiresJobApproval ?? false,
    isActive: item.is_active !== false,
  };
}

async function loadRoles(): Promise<ExternalRole[]> {
  const res = await fetch(`${API}/api/admin/roles?audience=EXTERNAL`);
  if (!res.ok) return [];
  const data = await res.json();
  const rows = Array.isArray(data) ? data : (data.roles || []);
  return rows.map(parseRole);
}

async function loadRoleByKey(roleKey: string): Promise<ExternalRole | null> {
  const roles = await loadRoles();
  const key = roleKey.toLowerCase();
  return roles.find((item) => item.roleKey.toLowerCase() === key) || null;
}

export default function RoleUiConfigsViewPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const roleKey = createMemo(() => {
    const val = searchParams.roleKey;
    return (Array.isArray(val) ? val[0] : val) || '';
  });
  const [rows] = createResource(loadRoles);
  const [selected] = createResource(roleKey, async (key) => (key ? loadRoleByKey(key) : null));
  const permissionActions = ['read', 'create', 'update', 'delete', 'approve'];

  const approvalFlags = createMemo(() => {
    const value = selected();
    if (!value) return [] as string[];
    const flags: string[] = [];
    if (value.requiresOnboardingApproval) flags.push('Onboarding Approval');
    if (value.requiresLeadApproval) flags.push('Lead Approval');
    if (value.requiresJobApproval) flags.push('Job Approval');
    return flags;
  });

  return (
      <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 Dashboard Management</h1>
        <p class="text-sm text-gray-500 mt-0.5">Read-only view of the currently published external dashboard and runtime role configuration.</p>
      </div>
      <div class="p-6">

      <ExternalRoleTabs roleKey={roleKey()} />

      <div style="display:grid;grid-template-columns:420px minmax(0,1fr);gap:16px">
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
          <div class="list-header">
            <h2 style="margin:0">External Dashboard Roles</h2>
            <A class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/roles">Open Roles</A>
          </div>
          <p class="notice" style="margin-top:2px">
            Select a role to inspect its published dashboard modules, profile-flow assignment, and permissions.
          </p>

          <Show when={rows.loading}>
            <p class="notice">Loading runtime role configs...</p>
          </Show>
          <Show when={!rows.loading && (rows()?.length || 0) === 0}>
            <p class="notice">No runtime roles available.</p>
          </Show>

          <div style="margin-top:12px;display:flex;flex-direction:column;gap:10px">
            <For each={rows() || []}>{(item) => {
              const isActive = roleKey().toLowerCase() === item.roleKey.toLowerCase();
              return (
                <button
                  type="button"
                  onClick={() => navigate(`/admin/role-ui-configs?roleKey=${encodeURIComponent(item.roleKey)}`)}
                  style={`text-align:left;border:1px solid ${isActive ? '#0a1d37' : '#e2e8f0'};border-radius:12px;padding:12px;background:${isActive ? '#f0f4f9' : '#fff'}`}
                >
                  <div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
                    <div>
                      <p style="margin:0;font-size:14px;font-weight:700;color:#0f172a">{item.displayName}</p>
                      <p style="margin:3px 0 0;font-size:11px;color:#64748b">{item.roleKey}</p>
                    </div>
                    <span class={`status-pill ${item.isActive ? 'status-approved' : 'status-rejected'}`}>{item.isActive ? 'Active' : 'Inactive'}</span>
                  </div>
                  <p class="notice" style="margin-top:8px">{item.enabledModules.length} modules • profile flow {item.onboardingSchemaId || 'Dashboard-first'}</p>
                </button>
              );
            }}</For>
          </div>
        </section>

        <section style="display:flex;flex-direction:column;gap:12px">
          <div class="rounded-xl border border-gray-200 bg-white shadow-sm">
            <div class="list-header">
              <div>
                <h2 style="margin:0">Dashboard Detail</h2>
                <p class="notice" style="margin-top:3px">This page is the safe inspector for published external dashboard and role configuration.</p>
              </div>
              <Show when={selected()}>
                <A class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href={`/admin/external-roles?editingId=${encodeURIComponent(selected()!.id)}`}>Open Role Detail</A>
              </Show>
            </div>
          </div>

          <Show when={selected.loading}>
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Loading config detail...</p></div>
          </Show>
          <Show when={!selected.loading && !selected() && roleKey()}>
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">No runtime role found for "{roleKey()}".</p></div>
          </Show>
          <Show when={!selected.loading && !selected() && !roleKey()}>
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Select an external role to view its current dashboard configuration.</p></div>
          </Show>
          <Show when={selected()}>
            <div style="display:flex;flex-direction:column;gap:12px">
              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div class="kv-item"><p class="kv-label">Role Key</p><p class="kv-value">{selected()!.roleKey}</p></div>
                  <div class="kv-item"><p class="kv-label">Display Name</p><p class="kv-value">{selected()!.displayName}</p></div>
                  <div class="kv-item"><p class="kv-label">Vertical</p><p class="kv-value">{selected()!.vertical || '—'}</p></div>
                  <div class="kv-item">
                    <p class="kv-label">Status</p>
                    <p class="kv-value">
                      <span class={`status-pill ${selected()!.isActive ? 'status-approved' : 'status-rejected'}`}>{selected()!.isActive ? 'Active' : 'Inactive'}</span>
                    </p>
                  </div>
                  <div class="kv-item"><p class="kv-label">Role Category</p><p class="kv-value">{selected()!.roleCategory || '—'}</p></div>
                  <div class="kv-item"><p class="kv-label">Profile Flow</p><p class="kv-value">{selected()!.onboardingSchemaId || 'Dashboard-first'}</p></div>
                  <div class="kv-item"><p class="kv-label">Runtime Config Version</p><p class="kv-value">{selected()!.runtimeConfigVersion}</p></div>
                  <div class="kv-item">
                    <p class="kv-label">Approval Flags</p>
                    <p class="kv-value">
                      <Show when={approvalFlags().length > 0} fallback={'None'}>
                        <span style="display:inline-flex;gap:6px;flex-wrap:wrap">
                          <For each={approvalFlags()}>{(flag) => <span class="status-pill status-pending">{flag}</span>}</For>
                        </span>
                      </Show>
                    </p>
                  </div>
                </div>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin:0 0 8px">Enabled Modules</h2>
                <Show when={selected()!.enabledModules.length > 0} fallback={<p class="notice">No modules configured.</p>}>
                  <div style="display:flex;flex-wrap:wrap;gap:8px">
                    <For each={selected()!.enabledModules}>{(moduleKey) => <span class="meta-chip">{moduleKey}</span>}</For>
                  </div>
                </Show>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin:0 0 8px">Permission Matrix</h2>
                <div class="overflow-x-auto">
                  <table class="w-full text-sm">
                    <thead>
                      <tr>
                        <th>Module</th>
                        <For each={permissionActions}>{(action) => <th class="text-right">{action}</th>}</For>
                      </tr>
                    </thead>
                    <tbody>
                      <For each={selected()!.enabledModules}>{(moduleKey) => (
                        <tr>
                          <td>{moduleKey}</td>
                          <For each={permissionActions}>{(action) => (
                            <td class="text-right">
                              <input type="checkbox" checked={(selected()!.permissions[moduleKey] || []).includes(action)} disabled />
                            </td>
                          )}</For>
                        </tr>
                      )}</For>
                    </tbody>
                  </table>
                </div>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin:0 0 8px">Feature Limits</h2>
                <pre class="json">{JSON.stringify(selected()!.featureLimits || {}, null, 2)}</pre>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin:0 0 8px">Published Runtime Config</h2>
                <pre class="json">{JSON.stringify(selected(), null, 2)}</pre>
              </section>
            </div>
          </Show>
        </section>
      </div>
      </div>
      </div>
  );
}
