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

const API = '/api/gateway';

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 loadLeads(): Promise<any[]> {
  try {
    const res = await fetch(`${API}/api/admin/leads`);
    if (res.ok) {
      const data = await res.json();
      return Array.isArray(data) ? data : (data.leads || []);
    }
    const res2 = await fetch(`${API}/api/leads?limit=100`);
    if (!res2.ok) throw new Error('Failed to load');
    const data2 = await res2.json();
    return Array.isArray(data2) ? data2 : (data2.leads || []);
  } catch {
    return [];
  }
}

export default function LeadsPage() {
  const [leads] = createResource(loadLeads);
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal('');
  const [roleFilter, setRoleFilter] = createSignal('');

  const filtered = createMemo(() => {
    const list = leads() ?? [];
    const q = search().toLowerCase();
    const sf = statusFilter().toUpperCase();
    const rf = roleFilter().toLowerCase();
    return list.filter((item) => {
      const title = (item.title || '').toLowerCase();
      const loc = (item.location || '').toLowerCase();
      const matchQ = !q || title.includes(q) || loc.includes(q);
      const matchS = !sf || (item.status || '').toUpperCase() === sf;
      const matchR = !rf || (item.profession || item.role || '').toLowerCase() === rf;
      return matchQ && matchS && matchR;
    });
  });

  return (
    <AdminShell>
      <div class="mb-6 flex items-start justify-between gap-4">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">Leads Management</h1>
          <p class="mt-1 text-sm text-gray-500">View all requirements and lead requests from customers.</p>
        </div>
      </div>

      {/* Filters */}
      <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px;align-items:center;">
        <input
          type="text"
          placeholder="Search by title or location..."
          value={search()}
          onInput={(e) => setSearch(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:8px;padding:8px 12px;font-size:14px;outline:none;min-width:220px;flex:1;max-width:320px"
        />
        <select
          value={statusFilter()}
          onChange={(e) => setStatusFilter(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:8px;padding:8px 12px;font-size:14px;background:#fff;outline:none;"
        >
          <option value="">All Statuses</option>
          <option value="OPEN">Open</option>
          <option value="ACTIVE">Active</option>
          <option value="PENDING">Pending</option>
          <option value="CLOSED">Closed</option>
          <option value="CANCELLED">Cancelled</option>
        </select>
        <select
          value={roleFilter()}
          onChange={(e) => setRoleFilter(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:8px;padding:8px 12px;font-size:14px;background:#fff;outline:none;"
        >
          <option value="">All Roles</option>
          <For each={ROLE_OPTIONS}>
            {(r) => <option value={r}>{r.replace(/_/g, ' ')}</option>}
          </For>
        </select>
        <Show when={search() || statusFilter() || roleFilter()}>
          <span style="font-size:13px;color:#64748b">{filtered().length} result{filtered().length !== 1 ? 's' : ''}</span>
        </Show>
      </div>

      <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="padding: 0; overflow: hidden;">
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr>
                <th>Title</th>
                <th>Role</th>
                <th>Budget</th>
                <th>Location</th>
                <th>Status</th>
                <th class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={leads.loading}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#64748b">Loading leads...</td></tr>
              </Show>
              <Show when={!leads.loading && leads.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={!leads.loading && !leads.error && filtered().length === 0}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#94a3b8">No leads found.</td></tr>
              </Show>
              <Show when={!leads.loading && !leads.error && filtered().length > 0}>
                <For each={filtered()}>
                  {(item) => (
                    <tr>
                      <td>
                        <div style="font-weight:600;color:#0f172a">{item.title || '—'}</div>
                        <Show when={item.description}>
                          <div style="font-size:12px;color:#64748b;margin-top:2px">
                            {String(item.description).slice(0, 60)}{String(item.description).length > 60 ? '…' : ''}
                          </div>
                        </Show>
                      </td>
                      <td style="color:#475569">{item.profession || item.role || '—'}</td>
                      <td style="color:#475569">
                        {item.budget_range || (item.budget_min != null ? `₹${item.budget_min}–₹${item.budget_max}` : '—')}
                      </td>
                      <td style="color:#475569">{item.location || '—'}</td>
                      <td>
                        <span class={`inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600 ${(item.status === 'ACTIVE' || item.status === 'OPEN') ? 'active' : ''}`}>
                          {item.status || '—'}
                        </span>
                      </td>
                      <td>
                        <div class="flex items-center justify-end gap-1">
                          <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/leads/${item.id}`}>View</A>
                        </div>
                      </td>
                    </tr>
                  )}
                </For>
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
