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=job_seeker`);
    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 CandidatePage() {
  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="page-actions">
        <div>
          <h1 class="page-title">Candidate Management</h1>
          <p class="page-subtitle">Manage all job seeker accounts on the platform.</p>
        </div>
      </div>

      <section class="card" style="padding: 0; overflow: hidden;">
        <div style="display:flex;gap:12px;padding:16px;border-bottom:1px solid #e2e8f0;flex-wrap:wrap;">
          <input
            type="text"
            placeholder="Search by name or email..."
            value={search()}
            onInput={(e) => setSearch(e.currentTarget.value)}
            style="border:1px solid #cbd5e1;border-radius:6px;padding:8px 12px;font-size:14px;width:260px;"
          />
          <select
            value={statusFilter()}
            onChange={(e) => setStatusFilter(e.currentTarget.value)}
            style="border:1px solid #cbd5e1;border-radius:6px;padding:8px 12px;font-size:14px;"
          >
            <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-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
                <th>Registered</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={users.loading}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
              </Show>
              <Show when={!users.loading && users.error}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
              </Show>
              <Show when={!users.loading && !users.error && filtered().length === 0}>
                <tr><td colspan="5" style="text-align:center;padding:32px;color:#94a3b8">No job seeker users found.</td></tr>
              </Show>
              <Show when={!users.loading && !users.error && filtered().length > 0}>
                <For each={filtered()}>
                  {(item) => (
                    <tr>
                      <td style="font-weight:600;color:#0f172a">{item.name || item.full_name || '—'}</td>
                      <td style="color:#475569">{item.email}</td>
                      <td>
                        {item.status?.toUpperCase() === 'ACTIVE' && (
                          <span class="status-chip active">ACTIVE</span>
                        )}
                        {item.status?.toUpperCase() === 'INACTIVE' && (
                          <span class="status-chip">INACTIVE</span>
                        )}
                        {item.status?.toUpperCase() === 'PENDING' && (
                          <span class="status-chip" style="background:#fff7ed;color:#c2410c;border-color:#fed7aa;">PENDING</span>
                        )}
                        {!item.status && <span class="status-chip">—</span>}
                      </td>
                      <td style="color:#475569">
                        {item.created_at ? new Date(item.created_at).toLocaleDateString() : '—'}
                      </td>
                      <td>
                        <div class="table-actions">
                          <A class="btn" href={`/admin/users/${item.id}`}>View</A>
                        </div>
                      </td>
                    </tr>
                  )}
                </For>
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
