import { A } from '@solidjs/router';
import { createResource, createSignal, For, Show } from 'solid-js';
import { Globe, ShieldCheck, ShieldOff, Layers, MoreVertical, Search, Plus } from 'lucide-solid';

const API = '';

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

const FALLBACK: ExternalRole[] = [
  { id: 'r1', roleKey: 'COMPANY', displayName: 'Company', vertical: 'Business', enabledModules: ['Jobs', 'Applications', 'Leads', 'Reports'], onboardingSchemaId: 'schema-company', isActive: true },
  { id: 'r2', roleKey: 'JOB_SEEKER', displayName: 'Job Seeker', vertical: 'Talent', enabledModules: ['Jobs', 'Applications', 'Profile'], onboardingSchemaId: 'schema-job-seeker', isActive: true },
  { id: 'r3', roleKey: 'CUSTOMER', displayName: 'Customer', vertical: 'Services', enabledModules: ['Services', 'Orders', 'Payments'], onboardingSchemaId: 'schema-customer', isActive: true },
  { id: 'r4', roleKey: 'PHOTOGRAPHER', displayName: 'Photographer', vertical: 'Professional', enabledModules: ['Portfolio', 'Leads', 'Reviews', 'Pricing'], onboardingSchemaId: 'schema-professional', isActive: true },
  { id: 'r5', roleKey: 'MAKEUP_ARTIST', displayName: 'Makeup Artist', vertical: 'Professional', enabledModules: ['Portfolio', 'Leads', 'Reviews'], onboardingSchemaId: 'schema-professional', isActive: false },
];

async function fetchExternalRoles(): Promise<{ roles: ExternalRole[]; error: string }> {
  try {
    const res = await fetch(`${API}/api/admin/roles?audience=EXTERNAL`);
    if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
    const data = await res.json();
    const rows = (Array.isArray(data) ? data : (data.roles ?? []))
      .filter((r: any) => String(r?.audience || '').toUpperCase() === 'EXTERNAL');
    const list: ExternalRole[] = rows.map((r: any) => {
      const cfg = r.config_json || {};
      return {
        id: String(r.id || ''),
        roleKey: String(r.key || r.role_key || r.roleKey || ''),
        displayName: r.name || r.displayName || r.display_name || r.key || '—',
        vertical: cfg?.vertical || r.vertical || '—',
        enabledModules: Array.isArray(cfg?.enabledModules) ? cfg.enabledModules : [],
        onboardingSchemaId: String(cfg?.onboardingSchemaId || r.onboarding_schema_id || ''),
        isActive: r.is_active !== false,
      };
    });
    return { roles: list, error: '' };
  } catch (e) {
    console.error(e);
    return {
      roles: FALLBACK,
      error: 'Failed to load external roles from the server. Showing sample data — changes here will not be saved.',
    };
  }
}

function StatusBadge(props: { active: boolean }) {
  return (
    <span class={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold ${props.active ? 'bg-[#ECFDF5] text-[#059669]' : 'bg-[#F3F4F6] text-[#6B7280]'}`}>
      <span class={`h-1.5 w-1.5 rounded-full ${props.active ? 'bg-[#059669]' : 'bg-[#9CA3AF]'}`} />
      {props.active ? 'Active' : 'Inactive'}
    </span>
  );
}

export default function ExternalRolesPage() {
  const [result, { refetch }] = createResource(fetchExternalRoles);
  const roles = () => result()?.roles ?? [];
  const roleFetchLoading = () => result.loading;
  const loadError = () => result()?.error ?? '';
  const [search, setSearch] = createSignal('');
  const [openMenu, setOpenMenu] = createSignal('');
  const [deleting, setDeleting] = createSignal('');
  const [deleteError, setDeleteError] = createSignal('');

  const filtered = () => {
    const q = search().toLowerCase();
    return roles().filter(r =>
      !q || r.displayName.toLowerCase().includes(q) || r.roleKey.toLowerCase().includes(q) || r.vertical.toLowerCase().includes(q)
    );
  };

  const stats = () => {
    const list = roles();
    return { total: list.length, active: list.filter(r => r.isActive).length, inactive: list.filter(r => !r.isActive).length };
  };

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Delete external role "${name}"? This cannot be undone.`)) { setOpenMenu(''); return; }
    setDeleting(id); setOpenMenu(''); setDeleteError('');
    try {
      const res = await fetch(`${API}/api/admin/roles/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
      refetch();
    } catch (e) {
      console.error(e);
      setDeleteError(`Failed to delete "${name}". Please try again.`);
    }
    finally { setDeleting(''); }
  };

  return (
      <div class="w-full space-y-8 pb-8">

        {/* Page header */}
        <div class="flex items-end justify-between">
          <div>
            <p class="text-[12px] font-semibold uppercase tracking-widest text-[#FF5E13]">Access Control</p>
            <h1 class="mt-1 text-[28px] font-bold leading-tight text-[#111827]">External Role Management</h1>
            <p class="mt-1 text-[14px] text-[#6B7280]">Dashboard / External Role Management</p>
          </div>
          <A
            href="/admin/runtime-roles/new"
            class="inline-flex items-center gap-2 rounded-xl bg-[#FF5E13] px-5 py-2.5 text-[13px] font-semibold text-white hover:bg-[#e04d0a] transition-colors shadow-sm"
          >
            <Plus size={15} />
            Add External Role
          </A>
        </div>

        <Show when={loadError()}>
          <div class="rounded-xl border border-[#FECACA] bg-[#FEF2F2] px-4 py-3 text-[13px] font-medium text-[#B91C1C]">
            {loadError()}
          </div>
        </Show>
        <Show when={deleteError()}>
          <div class="rounded-xl border border-[#FECACA] bg-[#FEF2F2] px-4 py-3 text-[13px] font-medium text-[#B91C1C]">
            {deleteError()}
          </div>
        </Show>

        {/* Stat cards */}
        <div class="grid grid-cols-2 gap-5 lg:grid-cols-4">
          <For each={[
            { label: 'Total Roles', value: () => stats().total, Icon: Globe, bg: 'bg-[#FFF1EB]', color: 'text-[#FF5E13]' },
            { label: 'Active Roles', value: () => stats().active, Icon: ShieldCheck, bg: 'bg-[#ECFDF5]', color: 'text-[#059669]' },
            { label: 'Inactive Roles', value: () => stats().inactive, Icon: ShieldOff, bg: 'bg-[#FEF2F2]', color: 'text-[#DC2626]' },
            { label: 'Total Modules', value: () => roles().reduce((a, r) => a + r.enabledModules.length, 0), Icon: Layers, bg: 'bg-[#EFF6FF]', color: 'text-[#2563EB]' },
          ]}>
            {(s) => (
              <div class="rounded-2xl border border-[#E5E7EB] bg-white p-5 shadow-sm">
                <div class="flex items-start justify-between">
                  <div>
                    <p class="text-[12px] font-medium text-[#6B7280]">{s.label}</p>
                    <p class="mt-3 text-[32px] font-bold leading-none text-[#111827]">{s.value()}</p>
                  </div>
                  <div class={`flex h-11 w-11 items-center justify-center rounded-xl ${s.bg}`}>
                    <s.Icon size={20} class={s.color} />
                  </div>
                </div>
              </div>
            )}
          </For>
        </div>

        {/* Table card */}
        <div class="rounded-2xl border border-[#E5E7EB] bg-white shadow-sm overflow-hidden">

          {/* Toolbar */}
          <div class="flex items-center gap-3 border-b border-[#F3F4F6] px-5 py-4">
            <div class="relative flex-1 max-w-[320px]">
              <Search size={14} class="absolute left-3 top-1/2 -translate-y-1/2 text-[#9CA3AF]" />
              <input
                type="text"
                placeholder="Search roles…"
                value={search()}
                onInput={e => setSearch(e.currentTarget.value)}
                class="h-[36px] w-full rounded-lg border border-[#E5E7EB] bg-[#F9FAFB] pl-9 pr-3 text-[13px] text-[#111827] outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] placeholder-[#9CA3AF]"
              />
            </div>
            <p class="ml-auto text-[12px] text-[#9CA3AF]">{filtered().length} role{filtered().length !== 1 ? 's' : ''}</p>
          </div>

          {/* Table */}
          <div class="overflow-x-auto">
            <table class="w-full min-w-[900px]">
              <thead>
                <tr class="border-b border-[#F3F4F6] bg-[#FAFAFA]">
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Role</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Role Key</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Vertical</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Enabled Modules</th>
                  <th class="px-5 py-3.5 text-center text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Status</th>
                  <th class="px-5 py-3.5 text-right text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Actions</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-[#F3F4F6]">

                <Show when={roleFetchLoading()}>
                  <For each={[1, 2, 3]}>
                    {() => (
                      <tr class="animate-pulse">
                        <td class="px-5 py-4"><div class="h-3 w-32 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4"><div class="h-5 w-24 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4"><div class="h-3 w-20 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4"><div class="h-5 w-20 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4 text-center"><div class="mx-auto h-5 w-16 rounded-full bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4" />
                      </tr>
                    )}
                  </For>
                </Show>

                <Show when={!roleFetchLoading() && filtered().length === 0}>
                  <tr>
                    <td colspan="6" class="px-5 py-16 text-center">
                      <div class="flex flex-col items-center gap-2">
                        <Globe size={32} class="text-[#E5E7EB]" />
                        <p class="text-[14px] font-medium text-[#6B7280]">No external roles found</p>
                      </div>
                    </td>
                  </tr>
                </Show>

                <For each={filtered()}>
                  {(role) => (
                    <tr class="hover:bg-[#FAFAFA] transition-colors">
                      <td class="px-5 py-4">
                        <p class="text-[13px] font-semibold text-[#111827]">{role.displayName}</p>
                      </td>
                      <td class="px-5 py-4">
                        <span class="inline-flex rounded-md bg-[#F3F4F6] px-2 py-1 font-mono text-[11px] text-[#374151]">{role.roleKey}</span>
                      </td>
                      <td class="px-5 py-4 text-[13px] text-[#374151]">{role.vertical}</td>
                      <td class="px-5 py-4">
                        <span class="inline-flex items-center gap-1 rounded-lg bg-[#EFF6FF] px-2.5 py-1 text-[11px] font-semibold text-[#2563EB]">
                          <Layers size={11} />
                          {role.enabledModules.length} modules
                        </span>
                      </td>
                      <td class="px-5 py-4 text-center">
                        <StatusBadge active={role.isActive} />
                      </td>
                      <td class="px-5 py-4">
                        <div class="flex justify-end">
                          <div class="relative">
                            <button
                              type="button"
                              onClick={() => setOpenMenu(openMenu() === role.id ? '' : role.id)}
                              class="flex h-8 w-8 items-center justify-center rounded-lg text-[#9CA3AF] hover:bg-[#F3F4F6] hover:text-[#374151] transition-colors"
                            >
                              <MoreVertical size={16} />
                            </button>
                            <Show when={openMenu() === role.id}>
                              <div class="absolute right-0 top-9 z-20 w-[190px] rounded-xl border border-[#E5E7EB] bg-white p-1.5 shadow-lg">
                                <A
                                  href={`/admin/runtime-roles/${encodeURIComponent(role.roleKey)}`}
                                  onClick={() => setOpenMenu('')}
                                  class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-[#374151] hover:bg-[#F3F4F6] transition-colors"
                                >
                                  <svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
                                  Edit Role
                                </A>
                                <div class="my-1 h-px bg-[#F3F4F6]" />
                                <button
                                  type="button"
                                  disabled={deleting() === role.id}
                                  onClick={() => handleDelete(role.id, role.displayName)}
                                  class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-[#DC2626] hover:bg-[#FEF2F2] transition-colors"
                                >
                                  <svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                  Delete Role
                                </button>
                              </div>
                            </Show>
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </For>
              </tbody>
            </table>
          </div>
        </div>

        <Show when={openMenu()}>
          <div class="fixed inset-0 z-10" onClick={() => setOpenMenu('')} />
        </Show>

      </div>
  );
}
