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

const API = '/api/gateway';

interface User {
  id: string;
  name?: string;
  full_name?: string;
  email: string;
  role?: string;
  role_name?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING';
  created_at?: string;
  createdAt?: string;
  roleId?: string;
  role_name?: string;
  userType?: string | number;
}

const ROLE_OPTIONS = [
  'company',
  'job_seeker',
  'customer',
  'photographer',
  'video_editor',
  'graphic_designer',
  'social_media_manager',
  'fitness_trainer',
  'catering_services',
  'makeup_artist',
  'tutor',
  'developer',
];

async function fetchUsers(): Promise<User[]> {
  try {
    const res = await fetch(`${API}/api/admin/users`);
    if (res.status === 404) {
      const res2 = await fetch(`${API}/api/users`);
      if (!res2.ok) throw new Error('Failed to load');
      const data2 = await res2.json();
      return Array.isArray(data2) ? data2 : (data2.users || []);
    }
    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(props: { status: string }) {
  if (props.status === 'ACTIVE') {
    return <span class="status-chip active">ACTIVE</span>;
  }
  if (props.status === 'PENDING') {
    return <span class="status-chip" style="background:#f59e0b;color:#fff">PENDING</span>;
  }
  return <span class="status-chip">INACTIVE</span>;
}

export default function UsersPage() {
  const [users, { refetch }] = createResource(fetchUsers);
  const [activeTab, setActiveTab] = createSignal<'list' | 'view'>('list');
  const [selectedUser, setSelectedUser] = createSignal<User | null>(null);
  const [search, setSearch] = createSignal('');
  const [filterRole, setFilterRole] = createSignal('');
  const [filterStatus, setFilterStatus] = createSignal('');
  const [currentPage, setCurrentPage] = createSignal(1);
  const usersPerPage = 10;

  const filtered = createMemo(() => {
    const list = users() ?? [];
    const q = search().toLowerCase();
    const role = filterRole();
    const status = filterStatus();
    return list.filter((u) => {
      const name = (u.name || u.full_name || '').toLowerCase();
      const email = u.email.toLowerCase();
      const matchSearch = !q || name.includes(q) || email.includes(q);
      const matchRole = !role || u.role === role || u.role_name === role;
      const matchStatus = !status || u.status === status;
      return matchSearch && matchRole && matchStatus;
    });
  });

  const totalPages = createMemo(() => {
    const count = filtered().length;
    return Math.max(1, Math.ceil(count / usersPerPage));
  });

  const paginated = createMemo(() => {
    const page = currentPage();
    const start = (page - 1) * usersPerPage;
    return filtered().slice(start, start + usersPerPage);
  });

  const shortId = (id: string) => `${id.slice(0, 8)}...`;
  const registrationRole = (u: User) => (u.role_name || u.role || 'UNKNOWN').toUpperCase();

  const onView = (user: User) => {
    setSelectedUser(user);
    setActiveTab('view');
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">External User Management</h1>
          <p class="page-subtitle">Manage all external platform users.</p>
        </div>
      </div>

      <div class="admin-segmented">
        <button
          class={`admin-segment ${activeTab() === 'list' ? 'active' : ''}`}
          type="button"
          onClick={() => setActiveTab('list')}
        >
          User List
        </button>
        <button
          class={`admin-segment ${activeTab() === 'view' ? 'active' : ''}`}
          type="button"
          disabled={!selectedUser()}
          onClick={() => setActiveTab('view')}
        >
          View Details
        </button>
      </div>

      {/* Filters */}
      <Show when={activeTab() === 'list'}>
        <div class="card" style="margin-bottom:16px;display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
          <input
            type="text"
            placeholder="Search by name or email..."
            value={search()}
            onInput={(e) => {
              setSearch(e.currentTarget.value);
              setCurrentPage(1);
            }}
            style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;width:260px;outline:none;"
          />
          <select
            value={filterRole()}
            onChange={(e) => {
              setFilterRole(e.currentTarget.value);
              setCurrentPage(1);
            }}
            style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;background:#fff;outline:none;"
          >
            <option value="">All Roles</option>
            <For each={ROLE_OPTIONS}>
              {(r) => <option value={r}>{r}</option>}
            </For>
          </select>
          <select
            value={filterStatus()}
            onChange={(e) => {
              setFilterStatus(e.currentTarget.value);
              setCurrentPage(1);
            }}
            style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;background:#fff;outline:none;"
          >
            <option value="">All Status</option>
            <option value="ACTIVE">ACTIVE</option>
            <option value="INACTIVE">INACTIVE</option>
            <option value="PENDING">PENDING</option>
          </select>
          <Show when={!users.loading}>
            <span style="font-size:13px;color:#64748b;margin-left:auto;">
              Showing {paginated().length} of {filtered().length} users
            </span>
          </Show>
        </div>
      </Show>

      <Show when={activeTab() === 'list'}>
        <section class="card" style="padding: 0; overflow: hidden;">
          <div class="table-wrap">
            <table class="list-table">
              <thead>
                <tr>
                  <th>User ID</th>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Registration Role</th>
                  <th>Status</th>
                  <th>Created</th>
                  <th class="align-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <Show when={users.loading}>
                  <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                </Show>
                <Show when={!users.loading && users.error}>
                  <tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
                </Show>
                <Show when={!users.loading && !users.error && paginated().length === 0}>
                  <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No users found.</td></tr>
                </Show>
                <Show when={!users.loading && !users.error && paginated().length > 0}>
                  <For each={paginated()}>
                    {(item) => (
                      <tr>
                        <td style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:#64748b">{shortId(item.id)}</td>
                        <td style="font-weight:600;color:#0f172a">{item.name || item.full_name || '—'}</td>
                        <td style="color:#475569">{item.email}</td>
                        <td style="color:#475569">{registrationRole(item)}</td>
                        <td>
                          <StatusBadge status={item.status} />
                        </td>
                        <td style="color:#475569">
                          {(item.created_at || item.createdAt)
                            ? new Date((item.created_at || item.createdAt)!).toLocaleDateString()
                            : '—'}
                        </td>
                        <td>
                          <div class="table-actions">
                            <button class="action-icon-btn" type="button" onClick={() => onView(item)} title="View Details">👁</button>
                            <A class="action-icon-btn" href={`/admin/users/${item.id}/edit`} title="Edit User">✎</A>
                            <button class="action-icon-btn danger" type="button" title="Delete User">🗑</button>
                          </div>
                        </td>
                      </tr>
                    )}
                  </For>
                </Show>
              </tbody>
            </table>
          </div>
          <div class="admin-pagination">
            <button class="btn" type="button" disabled={currentPage() <= 1} onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}>
              Previous
            </button>
            <span>Page {currentPage()} of {totalPages()}</span>
            <button class="btn" type="button" disabled={currentPage() >= totalPages()} onClick={() => setCurrentPage((p) => Math.min(totalPages(), p + 1))}>
              Next
            </button>
          </div>
        </section>
      </Show>

      <Show when={activeTab() === 'view'}>
        <section class="card">
          <Show when={selectedUser()} fallback={<p class="notice">Select a user from list to view details.</p>}>
            <div class="list-header">
              <h2>User Details</h2>
              <button class="btn" type="button" onClick={() => setActiveTab('list')}>Back To List</button>
            </div>
            <div class="grid" style="margin-top:0">
              <div class="list-item">
                <h3>Profile</h3>
                <p><strong>User ID:</strong> {selectedUser()!.id}</p>
                <p><strong>Name:</strong> {selectedUser()!.name || selectedUser()!.full_name || '—'}</p>
                <p><strong>Email:</strong> {selectedUser()!.email}</p>
                <p><strong>Role:</strong> {registrationRole(selectedUser()!)}</p>
                <p><strong>Status:</strong> {selectedUser()!.status}</p>
              </div>
              <div class="list-item">
                <h3>Account</h3>
                <p><strong>Created:</strong> {(selectedUser()!.created_at || selectedUser()!.createdAt) ? new Date((selectedUser()!.created_at || selectedUser()!.createdAt)!).toLocaleString() : '—'}</p>
                <p><strong>Role ID:</strong> {selectedUser()!.roleId || '—'}</p>
                <div class="actions">
                  <A class="btn navy" href={`/admin/users/${selectedUser()!.id}/edit`}>Edit User</A>
                  <button class="btn danger" type="button">Deactivate</button>
                </div>
              </div>
            </div>
          </Show>
        </section>
      </Show>
    </AdminShell>
  );
}
