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

const API = '';

type SortMode = 'newest' | 'oldest' | 'name_asc' | 'name_desc';

async function fetchProfessionList(endpoint: string): Promise<any[]> {
  try {
    const res = await fetch(`${API}${endpoint}`);
    if (!res.ok) throw new Error(`Failed to load: ${res.status}`);
    const data = await res.json();
    return Array.isArray(data) ? data : [];
  } catch (e) {
    console.error(`Failed to fetch from ${endpoint}:`, e);
    return [];
  }
}

function StatusBadge(props: { status?: string }) {
  const normalized = () => String(props.status || '').toUpperCase();
  const active = () => normalized() === 'ACTIVE';
  const pending = () => normalized() === 'PENDING';
  return (
    <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${active() ? '#FFD8C2' : pending() ? '#F6D78F' : '#D1D5DB'};background:${active() ? '#FFF1EB' : pending() ? '#FFF3D6' : '#F3F4F6'};color:${active() ? '#FF5E13' : pending() ? '#B7791F' : '#4B5563'};padding:2px 10px;font-size:12px;font-weight:500`}>
      <span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${active() ? '#FF5E13' : pending() ? '#B7791F' : '#9CA3AF'};margin-right:5px;flex-shrink:0`} />
      {normalized() ? normalized().charAt(0) + normalized().slice(1).toLowerCase() : 'Inactive'}
    </span>
  );
}

export default function ProfessionAdminListPage(props: {
  endpoint: string;
  title: string;
  subtitle: string;
  emptyLabel: string;
  viewHref: (id: string) => string;
  nameField?: string;
  createHref?: string;
}) {
  const nameField = props.nameField || 'first_name';
  const [items] = createResource(() => props.endpoint, fetchProfessionList);
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'ACTIVE' | 'INACTIVE' | 'PENDING'>('all');
  const [sortBy, setSortBy] = createSignal<SortMode>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);
  const [openMenuId, setOpenMenuId] = createSignal<string | null>(null);

  const filtered = createMemo(() => {
    const list = items() ?? [];
    const q = search().toLowerCase().trim();
    const f = statusFilter();
    const sorted = list.filter((u) => {
      const firstName = String(u.first_name || '').toLowerCase();
      const lastName = String(u.last_name || '').toLowerCase();
      const fullName = `${firstName} ${lastName}`.trim();
      const email = String(u.email || '').toLowerCase();
      const st = String(u.status || '').toUpperCase();
      const matchesSearch = !q || fullName.includes(q) || email.includes(q);
      const matchesStatus = f === 'all' || st === f;
      return matchesSearch && matchesStatus;
    });

    sorted.sort((a, b) => {
      const aDate = new Date(a.created_at || 0).getTime();
      const bDate = new Date(b.created_at || 0).getTime();
      if (sortBy() === 'oldest') return aDate - bDate;
      if (sortBy() === 'name_asc') return `${a.first_name || ''} ${a.last_name || ''}`.localeCompare(`${b.first_name || ''} ${b.last_name || ''}`);
      if (sortBy() === 'name_desc') return `${b.first_name || ''} ${b.last_name || ''}`.localeCompare(`${a.first_name || ''} ${a.last_name || ''}`);
      return bDate - aDate;
    });

    return sorted;
  });

  const exportCsv = () => {
    const headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Status', 'Registered'];
    const rows = filtered().map((item) => [
      String(item.first_name || ''),
      String(item.last_name || ''),
      String(item.email || ''),
      String(item.phone || ''),
      String(item.status || ''),
      item.created_at ? new Date(item.created_at).toLocaleDateString() : '',
    ]);
    const csv = [headers, ...rows]
      .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 = `${props.title.toLowerCase().replace(/\s+/g, '-')}-export.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]">{props.title}</h1>
           <p class="mt-1 text-[14px] text-[#6B7280]">{props.subtitle}</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;position:relative;z-index:20;">
             <input
               type="text"
               placeholder="Search by name or email..."
               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"
               >
                 <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                 Sort
               </button>
               <Show when={sortMenuOpen()}>
                 <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                   <For each={[
                     { key: 'newest', label: 'Newest First' },
                     { key: 'oldest', label: 'Oldest First' },
                     { key: 'name_asc', label: 'Name A-Z' },
                     { key: 'name_desc', label: 'Name Z-A' },
                   ] as { key: SortMode; label: string }[]}>
                     {(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"
               >
                 <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                 Filters
               </button>
               <Show when={filterMenuOpen()}>
                 <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                   <For each={[
                     { key: 'all', label: 'All Status' },
                     { key: 'ACTIVE', label: 'Active' },
                     { key: 'INACTIVE', label: 'Inactive' },
                     { key: 'PENDING', label: 'Pending' },
                   ] as { key: 'all' | 'ACTIVE' | 'INACTIVE' | 'PENDING'; label: string }[]}>
                     {(item) => (
                       <button
                         type="button"
                         onClick={() => { setStatusFilter(item.key); setFilterMenuOpen(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:${statusFilter() === item.key ? '#FF5E13' : '#374151'};background:${statusFilter() === item.key ? '#FFF1EB' : 'transparent'}`}
                       >
                         {item.label}
                       </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"
             >
               <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
               Export
             </button>
           </div>

           <div class="table-card">
             <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">Name</th>
                     <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Email</th>
                     <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Phone</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">Registered</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={items.loading}>
                     <tr><td colspan="6" class="px-6 py-16 text-center text-slate-500">Loading...</td></tr>
                   </Show>
                   <Show when={!items.loading && items.error}>
                     <tr><td colspan="6" class="px-6 py-16 text-center text-red-700">Failed to load. Is the backend running?</td></tr>
                   </Show>
                   <Show when={!items.loading && !items.error && filtered().length === 0}>
                     <tr>
                       <td colspan="6" class="px-6 py-16 text-center">
                         <p class="text-[15px] font-semibold text-[#111827]">No {props.title} found</p>
                         <p class="mt-1 text-[13px] text-[#6B7280]">{props.emptyLabel}</p>
                         {props.createHref && (
                           <A class="mt-4 inline-flex items-center gap-2 rounded-xl bg-[#0D0D2A] px-4 py-2 text-[13px] font-semibold text-white" href={props.createHref}>Create {props.title}</A>
                         )}
                       </td>
                     </tr>
                   </Show>
                   <Show when={!items.loading && !items.error && filtered().length > 0}>
                     <For each={filtered()}>
                       {(item) => (
                         <tr class="hover:bg-[#FAFAFA] transition-colors">
                           <td class="px-6 py-4">
                             <p class="font-semibold text-slate-900">{item.first_name || ''} {item.last_name || ''}</p>
                           </td>
                           <td class="px-6 py-4 text-slate-500">{item.email}</td>
                           <td class="px-6 py-4 text-slate-500">{item.phone || '—'}</td>
                           <td class="px-6 py-4"><StatusBadge status={item.status} /></td>
                           <td class="px-6 py-4 text-slate-500">{item.created_at ? new Date(item.created_at).toLocaleDateString() : '—'}</td>
                           <td class="px-6 py-4 text-right" style="position:relative">
                             <button type="button" onClick={() => setOpenMenuId(openMenuId() === String(item.id) ? null : String(item.id))} style="display:inline-flex;height:32px;width:32px;align-items:center;justify-content:center;border-radius:8px;color:#9CA3AF;background:none;border:none;cursor:pointer">
                               <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/></svg>
                             </button>
                             <Show when={openMenuId() === String(item.id)}>
                               <div style="position:absolute;right:20px;top:44px;z-index:20;width:180px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 20px rgba(0,0,0,0.12);text-align:left">
                                 <A href={props.viewHref(String(item.id))} class="block rounded-lg px-3 py-2 text-[13px] text-[#374151] hover:bg-[#F9FAFB]">View Profile</A>
                               </div>
                             </Show>
                           </td>
                         </tr>
                       )}
                     </For>
                   </Show>
                 </tbody>
               </table>
             </div>
           </div>

           {/* Pagination (matches department style, non-functional placeholder) */}
           <Show when={!items.loading && !items.error && filtered().length > 0}>
             <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px;margin-top:1px">
               <p style="font-size:13px;color:#6B7280">
                 Showing <strong style="font-weight:600;color:#111827">1–{filtered().length}</strong> of <strong style="font-weight:600;color:#111827">{filtered().length}</strong> {props.title.toLowerCase()}
               </p>
               <div style="display:flex;align-items:center;gap:4px">
                 <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">‹</button>
                 <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;background:#FF5E13;color:white;font-size:13px;font-weight:600;border:none;cursor:pointer">1</button>
                 <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">2</button>
                 <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">3</button>
                 <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">›</button>
               </div>
             </div>
           </Show>
         </div>
       </div>
   );
}
