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

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', 'ugc_content_creator',
];

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 [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'title_asc' | 'title_desc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);

  const filtered = createMemo(() => {
    const list = leads() ?? [];
    const q = search().toLowerCase();
    const sf = statusFilter().toUpperCase();
    const rf = roleFilter().toLowerCase();
    const rows = 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;
    });
    rows.sort((a, b) => {
      if (sortBy() === 'title_asc') return String(a.title || '').localeCompare(String(b.title || ''));
      if (sortBy() === 'title_desc') return String(b.title || '').localeCompare(String(a.title || ''));
      const aDate = new Date(a.created_at || a.updated_at || 0).getTime();
      const bDate = new Date(b.created_at || b.updated_at || 0).getTime();
      if (sortBy() === 'oldest') return aDate - bDate;
      return bDate - aDate;
    });
    return rows;
  });

  const exportCsv = () => {
    const headers = ['Title', 'Role', 'Budget', 'Location', 'Status'];
    const body = filtered().map((item) => [
      String(item.title || ''),
      String(item.profession || item.role || ''),
      String(item.budget_range || (item.budget_min != null ? `₹${item.budget_min}–₹${item.budget_max}` : '')),
      String(item.location || ''),
      String(item.status || ''),
    ]);
    const csv = [headers, ...body]
      .map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'leads.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <h1 class="text-xl font-semibold text-gray-900">Leads Management</h1>
          <p class="text-sm text-gray-500 mt-0.5">View all requirements and lead requests from customers.</p>
        </div>

        <div class="flex-1 p-6">
          {/* 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>
            <div style="position:relative">
              <button
                type="button"
                onClick={() => setSortMenuOpen((v) => !v)}
                style="display:inline-flex;height:38px;align-items:center;gap:6px;border-radius:8px;border:1px solid #cbd5e1;background:white;padding:0 12px;font-size:13px;font-weight:500;color:#374151;cursor:pointer"
              >
                Sort
              </button>
              <Show when={sortMenuOpen()}>
                <div style="position:absolute;left:0;top:42px;z-index:30;min-width:180px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                  {([
                    { key: 'newest', label: 'Newest First' },
                    { key: 'oldest', label: 'Oldest First' },
                    { key: 'title_asc', label: 'Title (A-Z)' },
                    { key: 'title_desc', label: 'Title (Z-A)' },
                  ] as const).map((item) => (
                    <button type="button" onClick={() => { setSortBy(item.key); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === item.key ? '#FF5E13' : '#374151'};background:${sortBy() === item.key ? '#FFF1EB' : 'transparent'}`}>
                      {item.label}
                    </button>
                  ))}
                </div>
              </Show>
            </div>
            <button
              type="button"
              onClick={exportCsv}
              style="display:inline-flex;height:38px;align-items:center;gap:6px;border-radius:8px;border:1px solid #D1D5DB;background:#fff;padding:0 12px;font-size:13px;font-weight:600;color:#0f172a;cursor:pointer"
            >
              Export
            </button>
            <Show when={search() || statusFilter() || roleFilter()}>
              <span style="font-size:13px;color:#64748b">{filtered().length} result{filtered().length !== 1 ? 's' : ''}</span>
            </Show>
          </div>

          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table 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 class="hover:bg-slate-50">
                          <td>
                            <div class="font-semibold text-slate-900">{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 class="text-slate-500">{item.profession || item.role || '—'}</td>
                          <td class="text-slate-500">
                            {item.budget_range || (item.budget_min != null ? `₹${item.budget_min}–₹${item.budget_max}` : '—')}
                          </td>
                          <td class="text-slate-500">{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>
          </div>
        </div>
      </div>
  );
}
