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

const API = '';

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 accessToken = typeof sessionStorage !== 'undefined'
      ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
      : '';
    const res = await fetch('/api/admin/leads', {
      headers: {
        Accept: 'application/json',
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: 'include',
    });
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.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 [filterMenuOpen, setFilterMenuOpen] = 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="w-full space-y-6 pb-8">
        <div style="margin-bottom:1.5rem">
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Leads Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">View all requirements and lead requests from customers.</p>
        </div>

        <div style="margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:hidden;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
            <input
              type="text"
              placeholder="Search by title or location..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
            />
            <div style="position:relative">
              <button
                type="button"
                onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;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)">
                  <For each={[
                    { 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}>{(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>
                  )}</For>
                </div>
              </Show>
            </div>
            <div style="position:relative">
              <button
                type="button"
                onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
              >
                Filters
              </button>
              <Show when={filterMenuOpen()}>
                <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                  <p style="font-size:11px;color:#9CA3AF;text-transform:uppercase;letter-spacing:0.05em;padding:4px 8px">Status</p>
                  <For each={[
                    { key: '', label: 'All Statuses' },
                    { key: 'OPEN', label: 'Open' },
                    { key: 'ACTIVE', label: 'Active' },
                    { key: 'PENDING', label: 'Pending' },
                    { key: 'CLOSED', label: 'Closed' },
                    { key: 'CANCELLED', label: 'Cancelled' },
                  ] as const}>{(item) => (
                    <button type="button" onClick={() => { setStatusFilter(item.key); setFilterMenuOpen(false); }} style={`display:block;width:100%;border:none;background:${statusFilter() === item.key ? '#FFF1EB' : 'transparent'};color:${statusFilter() === item.key ? '#FF5E13' : '#374151'};padding:8px 10px;border-radius:8px;text-align:left;font-size:13px;cursor:pointer`}>{item.label}</button>
                  )}</For>
                  <div style="height:1px;background:#F3F4F6;margin:6px 0" />
                  <p style="font-size:11px;color:#9CA3AF;text-transform:uppercase;letter-spacing:0.05em;padding:4px 8px">Role</p>
                  <button type="button" onClick={() => { setRoleFilter(''); setFilterMenuOpen(false); }} style={`display:block;width:100%;border:none;background:${roleFilter() === '' ? '#FFF1EB' : 'transparent'};color:${roleFilter() === '' ? '#FF5E13' : '#374151'};padding:8px 10px;border-radius:8px;text-align:left;font-size:13px;cursor:pointer`}>All Roles</button>
                  <For each={ROLE_OPTIONS}>
                    {(r) => (
                      <button type="button" onClick={() => { setRoleFilter(r); setFilterMenuOpen(false); }} style={`display:block;width:100%;border:none;background:${roleFilter() === r ? '#FFF1EB' : 'transparent'};color:${roleFilter() === r ? '#FF5E13' : '#374151'};padding:8px 10px;border-radius:8px;text-align:left;font-size:13px;cursor:pointer`}>{r.replace(/_/g, ' ')}</button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <button
              type="button"
              onClick={exportCsv}
              style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              Export
            </button>
          </div>

          <div class="overflow-x-auto">
              <table class="min-w-full">
                <thead>
                  <tr style="background:#0D0D2A;text-align:left">
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Title</th>
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Role</th>
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Budget</th>
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Location</th>
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Status</th>
                    <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap;text-align: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-[#FAFAFA] transition-colors" style="border-bottom:1px solid #F3F4F6">
                          <td style="padding:12px 20px">
                            <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 style="padding:12px 20px" class="text-slate-500">{item.profession || item.role || '—'}</td>
                          <td style="padding:12px 20px" class="text-slate-500">
                            {item.budget_range || (item.budget_min != null ? `₹${item.budget_min}–₹${item.budget_max}` : '—')}
                          </td>
                          <td style="padding:12px 20px" class="text-slate-500">{item.location || '—'}</td>
                          <td style="padding:12px 20px">
                            <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 style="padding:12px 20px">
                            <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>
  );
}
