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

const API = '/api/gateway';

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

async function fetchUsers(role: string): Promise<any[]> {
  try {
    const res = await fetch(`${API}/api/admin/users?role=${role.toUpperCase()}`);
    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(status?: string) {
  const normalized = (status || '').toUpperCase();
  if (normalized === 'ACTIVE') return 'inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700';
  if (normalized === 'PENDING') return 'inline-flex items-center rounded-full bg-orange-50 px-2.5 py-0.5 text-xs font-medium text-orange-700';
  return 'inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600';
}

export default function RoleUserManagementTablePage(props: {
  role: string;
  title: string;
  subtitle: string;
  emptyLabel: string;
  viewHref: (id: string) => string;
}) {
  const [users] = createResource(() => props.role, fetchUsers);
  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 filtered = createMemo(() => {
    const list = users() ?? [];
    const q = search().toLowerCase().trim();
    const f = statusFilter();
    const sorted = list.filter((u) => {
      const fullName = String(u.name || u.full_name || '').toLowerCase();
      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 String(a.name || a.full_name || '').localeCompare(String(b.name || b.full_name || ''));
      if (sortBy() === 'name_desc') return String(b.name || b.full_name || '').localeCompare(String(a.name || a.full_name || ''));
      return bDate - aDate;
    });

    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Name', 'Email', 'Status', 'Registered'];
    const rows = filtered().map((item) => [
      String(item.name || item.full_name || ''),
      String(item.email || ''),
      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.role}-users.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">{props.title}</h1>
          <p class="text-sm text-gray-500 mt-0.5">{props.subtitle}</p>
        </div>

        <div class="flex-1 p-6">
          <div class="mb-4 flex flex-wrap items-center gap-2" style="position:relative;z-index:20;">
            <input
              type="text"
              placeholder="Search by name or email..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              class="rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#FF5E13] w-72"
            />

            <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;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"
              >
                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;border:1px solid #D1D5DB;background:#fff;padding:0 12px;font-size:12px;font-weight:600;color:#0f172a;cursor:pointer"
            >
              Export
            </button>
          </div>

          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table w-full text-sm">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Status</th>
                    <th>Registered</th>
                    <th class="text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={users.loading}>
                    <tr><td colspan="5" class="text-center py-8 text-slate-500">Loading...</td></tr>
                  </Show>
                  <Show when={!users.loading && users.error}>
                    <tr><td colspan="5" class="text-center py-8 text-red-700">Failed to load. Is the backend running?</td></tr>
                  </Show>
                  <Show when={!users.loading && !users.error && filtered().length === 0}>
                    <tr><td colspan="5" class="text-center py-8 text-slate-400">{props.emptyLabel}</td></tr>
                  </Show>
                  <Show when={!users.loading && !users.error && filtered().length > 0}>
                    <For each={filtered()}>
                      {(item) => (
                        <tr class="hover:bg-slate-50">
                          <td class="font-semibold text-slate-900">{item.name || item.full_name || '—'}</td>
                          <td class="text-slate-500">{item.email}</td>
                          <td>
                            <span class={statusBadge(item.status)}>{item.status?.toUpperCase() || '—'}</span>
                          </td>
                          <td class="text-slate-500">{item.created_at ? new Date(item.created_at).toLocaleDateString() : '—'}</td>
                          <td>
                            <div class="flex items-center justify-end gap-1">
                              <A class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm hover:bg-gray-50" href={props.viewHref(String(item.id))}>View</A>
                            </div>
                          </td>
                        </tr>
                      )}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
  );
}
