'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { Input } from '@/components/input';
import { Button } from '@/components/ui/button';
import { ShieldCheck, Trash2 } from 'lucide-react';

interface AdminUser {
  id: string;
  email: string;
  name: string | null;
  isAdmin: boolean;
  emailVerified: boolean;
  lastLoginAt: string | null;
  createdAt: string;
  org: { orgId: string; orgName: string; orgSlug: string; plan: string; role: string } | null;
  serverCount: number;
}

export default function AdminUsersPage() {
  const [users, setUsers] = useState<AdminUser[] | null>(null);
  const [search, setSearch] = useState('');

  async function reload() {
    const r = await apiFetch<{ users: AdminUser[] }>(
      `/v1/admin/users${search ? `?search=${encodeURIComponent(search)}` : ''}`,
    );
    setUsers(r.users);
  }

  useEffect(() => {
    reload();
  }, [search]);

  async function toggleAdmin(u: AdminUser) {
    if (!confirm(`${u.isAdmin ? 'Revoke' : 'Grant'} admin for ${u.email}?`)) return;
    await apiFetch(`/v1/admin/users/${u.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ isAdmin: !u.isAdmin }),
    });
    reload();
  }

  async function remove(u: AdminUser) {
    if (!confirm(`Delete user ${u.email}? This cascades to their org and servers.`)) return;
    try {
      await apiFetch(`/v1/admin/users/${u.id}`, { method: 'DELETE' });
      reload();
    } catch (e) {
      const detail = (e as { detail?: { error?: string } }).detail;
      alert(`Failed: ${detail?.error ?? (e as Error).message}`);
    }
  }

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">Users</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          {users?.length ?? 0} total. Click admin toggle to elevate or revoke privileges.
        </p>
      </header>

      <div className="mb-4">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by email or name…"
          className="w-80"
        />
      </div>

      <div className="panel">
        {users === null && (
          <p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading…</p>
        )}
        {users && users.length === 0 && (
          <p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">No matches.</p>
        )}
        {users && users.length > 0 && (
          <table className="w-full text-[12.5px]">
            <thead className="border-b border-[--color-border] text-[--color-fg-subtle]">
              <tr>
                <th className="px-4 py-2 text-left font-medium">Email</th>
                <th className="px-4 py-2 text-left font-medium">Org</th>
                <th className="px-4 py-2 text-left font-medium">Plan</th>
                <th className="px-4 py-2 text-left font-medium">Servers</th>
                <th className="px-4 py-2 text-left font-medium">Last login</th>
                <th className="px-4 py-2 text-left font-medium">Joined</th>
                <th className="px-4 py-2 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id} className="border-b border-[--color-border] last:border-0">
                  <td className="px-4 py-2.5">
                    <div className="flex items-center gap-2">
                      {u.isAdmin && (
                        <span
                          className="inline-flex h-4 items-center gap-0.5 rounded-full border border-[--color-accent]/40 bg-[--color-accent]/10 px-1.5 text-[10px] font-medium text-[--color-accent]"
                          title="admin"
                        >
                          <ShieldCheck size={9} /> admin
                        </span>
                      )}
                      <span className="mono">{u.email}</span>
                    </div>
                    {u.name && (
                      <div className="text-[11px] text-[--color-fg-subtle]">{u.name}</div>
                    )}
                  </td>
                  <td className="px-4 py-2.5 text-[--color-fg-muted]">{u.org?.orgName ?? '—'}</td>
                  <td className="px-4 py-2.5">
                    <span className="mono rounded-full border border-[--color-border] bg-[--color-bg-subtle] px-2 py-0.5 text-[11px]">
                      {u.org?.plan ?? '—'}
                    </span>
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">{u.serverCount}</td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">
                    {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '—'}
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">
                    {new Date(u.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-2.5 text-right">
                    <div className="inline-flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => toggleAdmin(u)}>
                        {u.isAdmin ? 'revoke admin' : 'make admin'}
                      </Button>
                      <Button variant="danger" size="sm" onClick={() => remove(u)}>
                        <Trash2 size={11} />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
