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

const API = '/api/gateway';

interface User {
  id: string;
  name?: string;
  full_name?: string;
  email: string;
  role?: string;
  role_name?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING';
  created_at?: string;
  createdAt?: string;
}

const ROLE_OPTIONS = [
  'company',
  'job_seeker',
  'customer',
  'photographer',
  'video_editor',
  'graphic_designer',
  'social_media_manager',
  'fitness_trainer',
  'catering_services',
  'makeup_artist',
  'tutor',
  'developer',
];

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

function StatusBadge(props: { status: string }) {
  if (props.status === 'ACTIVE') {
    return <span class="status-chip active">ACTIVE</span>;
  }
  if (props.status === 'PENDING') {
    return <span class="status-chip" style="background:#f59e0b;color:#fff">PENDING</span>;
  }
  return <span class="status-chip">INACTIVE</span>;
}

export default function UsersPage() {
  const [users, { refetch }] = createResource(fetchUsers);
  const [search, setSearch] = createSignal('');
  const [filterRole, setFilterRole] = createSignal('');
  const [filterStatus, setFilterStatus] = createSignal('');

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

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">External User Management</h1>
          <p class="page-subtitle">Manage all external platform users.</p>
        </div>
      </div>

      {/* Filters */}
      <div class="card" style="margin-bottom:16px;display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
        <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:7px 12px;font-size:14px;width:260px;outline:none;"
        />
        <select
          value={filterRole()}
          onChange={(e) => setFilterRole(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;background:#fff;outline:none;"
        >
          <option value="">All Roles</option>
          <For each={ROLE_OPTIONS}>
            {(r) => <option value={r}>{r}</option>}
          </For>
        </select>
        <select
          value={filterStatus()}
          onChange={(e) => setFilterStatus(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;background:#fff;outline:none;"
        >
          <option value="">All Status</option>
          <option value="ACTIVE">ACTIVE</option>
          <option value="INACTIVE">INACTIVE</option>
          <option value="PENDING">PENDING</option>
        </select>
        <Show when={!users.loading}>
          <span style="font-size:13px;color:#64748b;margin-left:auto;">
            Showing {filtered().length} of {users()?.length ?? 0} users
          </span>
        </Show>
      </div>

      <section class="card" style="padding: 0; overflow: hidden;">
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Created At</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={users.loading}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
              </Show>
              <Show when={!users.loading && users.error}>
                <tr><td colspan="6" 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="6" style="text-align:center;padding:32px;color:#94a3b8">No 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 style="color:#475569">{item.role_name || item.role || '—'}</td>
                      <td>
                        <StatusBadge status={item.status} />
                      </td>
                      <td style="color:#475569">
                        {(item.created_at || item.createdAt)
                          ? new Date((item.created_at || item.createdAt)!).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>
  );
}
