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

const API = '/api/gateway';

async function fetchUsers(): Promise<any[]> {
  try {
    const res = await fetch(`${API}/api/admin/users?role=makeup_artist`);
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.users || []);
  } catch {
    return [];
  }
}

export default function MakeupArtistPage() {
  const [users] = createResource(fetchUsers);
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal('');

  const filtered = createMemo(() => {
    const list = users() ?? [];
    const q = search().toLowerCase();
    const s = statusFilter();
    return list.filter((u) => {
      const matchSearch =
        !q ||
        (u.name || u.full_name || '').toLowerCase().includes(q) ||
        (u.email || '').toLowerCase().includes(q);
      const matchStatus = !s || (u.status || '').toUpperCase() === s;
      return matchSearch && matchStatus;
    });
  });

  return (
    <AdminShell>
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        {/* White page header */}
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <h1 class="text-xl font-semibold text-gray-900">Makeup Artist Management</h1>
          <p class="text-sm text-gray-500 mt-0.5">Manage all makeup artist accounts on the platform.</p>
        </div>
        {/* Content */}
        <div class="flex-1 p-6">
          <div class="mb-4 flex flex-wrap items-center gap-3">
            <input
              type="text"
              placeholder="Search by name or email..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              class="rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#0a1d37] w-64"
            />
            <select
              value={statusFilter()}
              onChange={(e) => setStatusFilter(e.currentTarget.value)}
              class="rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#0a1d37]"
            >
              <option value="">All Status</option>
              <option value="ACTIVE">ACTIVE</option>
              <option value="INACTIVE">INACTIVE</option>
              <option value="PENDING">PENDING</option>
            </select>
          </div>

          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table w-full text-sm">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Status</th>
                    <th>Registered</th>
                    <th class="text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={users.loading}>
                    <tr><td colspan="5" class="text-center py-8 text-slate-500">Loading...</td></tr>
                  </Show>
                  <Show when={!users.loading && users.error}>
                    <tr><td colspan="5" class="text-center py-8 text-red-700">Failed to load. Is the backend running?</td></tr>
                  </Show>
                  <Show when={!users.loading && !users.error && filtered().length === 0}>
                    <tr><td colspan="5" class="text-center py-8 text-slate-400">No makeup artist users found.</td></tr>
                  </Show>
                  <Show when={!users.loading && !users.error && filtered().length > 0}>
                    <For each={filtered()}>
                      {(item) => (
                        <tr class="hover:bg-slate-50">
                          <td class="font-semibold text-slate-900">{item.name || item.full_name || '—'}</td>
                          <td class="text-slate-500">{item.email}</td>
                          <td>
                            {item.status?.toUpperCase() === 'ACTIVE' && (
                              <span class="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700">ACTIVE</span>
                            )}
                            {item.status?.toUpperCase() === 'INACTIVE' && (
                              <span class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">INACTIVE</span>
                            )}
                            {item.status?.toUpperCase() === 'PENDING' && (
                              <span class="inline-flex items-center rounded-full bg-orange-50 px-2.5 py-0.5 text-xs font-medium text-orange-700">PENDING</span>
                            )}
                            {!item.status && <span class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">—</span>}
                          </td>
                          <td class="text-slate-500">
                            {item.created_at ? new Date(item.created_at).toLocaleDateString() : '—'}
                          </td>
                          <td>
                            <div class="flex items-center justify-end gap-1">
                              <A class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm hover:bg-gray-50" href={`/admin/users/${item.id}`}>View</A>
                            </div>
                          </td>
                        </tr>
                      )}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </AdminShell>
  );
}
