/**
 * Shared page component for any "user list filtered by role" admin page.
 * Used by Photographer, Makeup Artist, Tutors, Developers, etc.
 */
import { createMemo, createResource, createSignal, For, Show, type JSX } from 'solid-js';
import { Search, MoreVertical, Users, UserCheck, UserX, Clock } from 'lucide-solid';

const API = '';

export interface UserListPageConfig {
  /** e.g. "photographer" */
  role: string;
  /** e.g. "Photographer Management" */
  title: string;
  /** e.g. "Professionals" */
  label: string;
  /** Lucide icon component */
  Icon: (props: { size?: number; class?: string }) => JSX.Element;
}

type User = {
  id: string;
  full_name?: string;
  name?: string;
  email: string;
  status?: string;
  is_active?: boolean;
  created_at?: string;
  phone?: string;
  city?: string;
};

function fetchUsers(role: string) {
  return async (): Promise<User[]> => {
    try {
      const res = await fetch(`${API}/api/admin/users?role=${role}`);
      if (!res.ok) throw new Error();
      const data = await res.json();
      return Array.isArray(data) ? data : (data.users ?? []);
    } catch {
      return [];
    }
  };
}

function userName(u: User) { return u.full_name || u.name || '—'; }
function isActive(u: User) {
  if (u.is_active !== undefined) return u.is_active;
  const s = String(u.status ?? '').toUpperCase();
  return s === 'ACTIVE' || s === '';
}
function fmtDate(d?: string) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return d; }
}
function initials(name: string) {
  return name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
}

function StatusBadge(props: { active: boolean }) {
  return (
    <span class={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold ${props.active ? 'bg-[#ECFDF5] text-[#059669]' : 'bg-[#F3F4F6] text-[#6B7280]'}`}>
      <span class={`h-1.5 w-1.5 rounded-full ${props.active ? 'bg-[#059669]' : 'bg-[#9CA3AF]'}`} />
      {props.active ? 'Active' : 'Inactive'}
    </span>
  );
}

export default function UserListPage(props: { config: UserListPageConfig }) {
  const [users] = createResource(fetchUsers(props.config.role));
  const [search, setSearch] = createSignal('');
  const [filterStatus, setFilterStatus] = createSignal('all');
  const [openMenu, setOpenMenu] = createSignal('');

  const filtered = createMemo(() => {
    const list = users() ?? [];
    const q = search().toLowerCase();
    return list.filter(u => {
      const matchQ = !q || userName(u).toLowerCase().includes(q) || u.email.toLowerCase().includes(q);
      const active = isActive(u);
      const matchS = filterStatus() === 'all' || (filterStatus() === 'active' && active) || (filterStatus() === 'inactive' && !active);
      return matchQ && matchS;
    });
  });

  const stats = createMemo(() => {
    const list = users() ?? [];
    const active = list.filter(u => isActive(u)).length;
    const pending = list.filter(u => String(u.status ?? '').toUpperCase() === 'PENDING').length;
    return { total: list.length, active, inactive: list.length - active - pending, pending };
  });

  const { Icon } = props.config;

  return (
      <div class="w-full space-y-8 pb-8">

        {/* Page header */}
        <div class="flex items-end justify-between">
          <div>
            <p class="text-[12px] font-semibold uppercase tracking-widest text-[#FF5E13]">{props.config.label}</p>
            <h1 class="mt-1 text-[28px] font-bold leading-tight text-[#111827]">{props.config.title}</h1>
            <p class="mt-1 text-[14px] text-[#6B7280]">Dashboard / {props.config.title}</p>
          </div>
        </div>

        {/* Stat cards */}
        <div class="grid grid-cols-2 gap-5 lg:grid-cols-4">
          <For each={[
            { label: 'Total', value: () => stats().total, Ic: Users, bg: 'bg-[#FFF1EB]', color: 'text-[#FF5E13]' },
            { label: 'Active', value: () => stats().active, Ic: UserCheck, bg: 'bg-[#ECFDF5]', color: 'text-[#059669]' },
            { label: 'Inactive', value: () => stats().inactive, Ic: UserX, bg: 'bg-[#FEF2F2]', color: 'text-[#DC2626]' },
            { label: 'Pending Verification', value: () => stats().pending, Ic: Clock, bg: 'bg-[#FFFBEB]', color: 'text-[#D97706]' },
          ]}>{(s) => (
            <div class="rounded-2xl border border-[#E5E7EB] bg-white p-5 shadow-sm">
              <div class="flex items-start justify-between">
                <div>
                  <p class="text-[12px] font-medium text-[#6B7280]">{s.label}</p>
                  <p class="mt-3 text-[32px] font-bold leading-none text-[#111827]">{s.value()}</p>
                </div>
                <div class={`flex h-11 w-11 items-center justify-center rounded-xl ${s.bg}`}>
                  <s.Ic size={20} class={s.color} />
                </div>
              </div>
            </div>
          )}</For>
        </div>

        {/* Table card */}
        <div class="rounded-2xl border border-[#E5E7EB] bg-white shadow-sm overflow-hidden">

          {/* Toolbar */}
          <div class="flex items-center gap-3 border-b border-[#F3F4F6] px-5 py-4">
            <div class="relative flex-1 max-w-[320px]">
              <Search size={14} class="absolute left-3 top-1/2 -translate-y-1/2 text-[#9CA3AF]" />
              <input
                type="text"
                placeholder={`Search ${props.config.title.replace(' Management', '').toLowerCase()}s…`}
                value={search()}
                onInput={e => setSearch(e.currentTarget.value)}
                class="h-[36px] w-full rounded-lg border border-[#E5E7EB] bg-[#F9FAFB] pl-9 pr-3 text-[13px] text-[#111827] outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] placeholder-[#9CA3AF]"
              />
            </div>
            <select
              value={filterStatus()}
              onChange={e => setFilterStatus(e.currentTarget.value)}
              class="h-[36px] rounded-lg border border-[#E5E7EB] bg-[#F9FAFB] px-3 text-[13px] text-[#374151] outline-none focus:border-[#FF5E13]"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
            <p class="ml-auto text-[12px] text-[#9CA3AF]">{filtered().length} record{filtered().length !== 1 ? 's' : ''}</p>
          </div>

          {/* Table */}
          <div class="overflow-x-auto">
            <table class="w-full min-w-[700px]">
              <thead>
                <tr class="border-b border-[#F3F4F6] bg-[#FAFAFA]">
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">User</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Phone</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">City</th>
                  <th class="px-5 py-3.5 text-left text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Joined</th>
                  <th class="px-5 py-3.5 text-center text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Status</th>
                  <th class="px-5 py-3.5 text-right text-[11px] font-semibold uppercase tracking-wider text-[#9CA3AF]">Actions</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-[#F3F4F6]">

                <Show when={users.loading}>
                  <For each={[1, 2, 3, 4]}>
                    {() => (
                      <tr class="animate-pulse">
                        <td class="px-5 py-4">
                          <div class="flex items-center gap-3">
                            <div class="h-9 w-9 rounded-full bg-[#F3F4F6]" />
                            <div class="space-y-1.5">
                              <div class="h-3 w-28 rounded bg-[#F3F4F6]" />
                              <div class="h-2.5 w-36 rounded bg-[#F3F4F6]" />
                            </div>
                          </div>
                        </td>
                        <td class="px-5 py-4"><div class="h-3 w-24 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4"><div class="h-3 w-20 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4"><div class="h-3 w-24 rounded bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4 text-center"><div class="mx-auto h-5 w-16 rounded-full bg-[#F3F4F6]" /></td>
                        <td class="px-5 py-4" />
                      </tr>
                    )}
                  </For>
                </Show>

                <Show when={!users.loading && filtered().length === 0}>
                  <tr>
                    <td colspan="6" class="px-5 py-16 text-center">
                      <div class="flex flex-col items-center gap-2">
                        <Icon size={32} class="text-[#E5E7EB]" />
                        <p class="text-[14px] font-medium text-[#6B7280]">No records found</p>
                        <p class="text-[12px] text-[#9CA3AF]">No {props.config.title.replace(' Management', '').toLowerCase()}s have registered yet.</p>
                      </div>
                    </td>
                  </tr>
                </Show>

                <For each={filtered()}>
                  {(user) => {
                    const active = () => isActive(user);
                    const name = userName(user);
                    return (
                      <tr class="hover:bg-[#FAFAFA] transition-colors">
                        <td class="px-5 py-4">
                          <div class="flex items-center gap-3">
                            <div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#F3F4F6] text-[11px] font-bold text-[#374151]">
                              {initials(name)}
                            </div>
                            <div>
                              <p class="text-[13px] font-semibold text-[#111827]">{name}</p>
                              <p class="text-[12px] text-[#9CA3AF]">{user.email}</p>
                            </div>
                          </div>
                        </td>
                        <td class="px-5 py-4 text-[13px] text-[#374151]">{user.phone || '—'}</td>
                        <td class="px-5 py-4 text-[13px] text-[#374151]">{user.city || '—'}</td>
                        <td class="px-5 py-4 text-[13px] text-[#374151]">{fmtDate(user.created_at)}</td>
                        <td class="px-5 py-4 text-center">
                          <StatusBadge active={active()} />
                        </td>
                        <td class="px-5 py-4">
                          <div class="flex justify-end">
                            <div class="relative">
                              <button
                                type="button"
                                onClick={() => setOpenMenu(openMenu() === user.id ? '' : user.id)}
                                class="flex h-8 w-8 items-center justify-center rounded-lg text-[#9CA3AF] hover:bg-[#F3F4F6] hover:text-[#374151] transition-colors"
                              >
                                <MoreVertical size={16} />
                              </button>
                              <Show when={openMenu() === user.id}>
                                <div class="absolute right-0 top-9 z-20 w-[180px] rounded-xl border border-[#E5E7EB] bg-white p-1.5 shadow-lg">
                                  <button
                                    type="button"
                                    onClick={() => setOpenMenu('')}
                                    class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-[#374151] hover:bg-[#F3F4F6] transition-colors"
                                  >
                                    <svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                                    View Profile
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => setOpenMenu('')}
                                    class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-[#374151] hover:bg-[#F3F4F6] transition-colors"
                                  >
                                    <svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>
                                    {active() ? 'Deactivate' : 'Activate'}
                                  </button>
                                </div>
                              </Show>
                            </div>
                          </div>
                        </td>
                      </tr>
                    );
                  }}
                </For>
              </tbody>
            </table>
          </div>
        </div>

        <Show when={openMenu()}>
          <div class="fixed inset-0 z-10" onClick={() => setOpenMenu('')} />
        </Show>

      </div>
  );
}
