'use client';

// User management UI. Same pattern as CategoryManager: local state
// mirrors the server data, mutations refresh the route. We hide the
// delete button for the current admin so they cannot lock themselves
// out, even though the service also enforces that rule.

import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { Button } from '@/components/ui/Button';

interface Row {
  id: number;
  name: string;
  email: string;
  role: 'ADMIN' | 'EMPLOYEE';
  createdAt: string;
}

export function UserManager({
  initial, currentUserId,
}: { initial: Row[]; currentUserId: number }) {
  const router = useRouter();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<'ADMIN' | 'EMPLOYEE'>('EMPLOYEE');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function addUser() {
    setError(null);
    setBusy(true);
    const res = await fetch('/api/admin/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, password, role }),
    });
    const json = await res.json();
    setBusy(false);
    if (!res.ok || !json.ok) { setError(json.error || 'Failed to add user'); return; }
    setName(''); setEmail(''); setPassword(''); setRole('EMPLOYEE');
    router.refresh();
  }

  async function changeRole(id: number, nextRole: 'ADMIN' | 'EMPLOYEE') {
    setBusy(true);
    await fetch(`/api/admin/users/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ role: nextRole }),
    });
    setBusy(false);
    router.refresh();
  }

  async function removeUser(id: number) {
    if (!confirm('Delete this user? Their questions and answers will remain in the system.')) return;
    setBusy(true);
    const res = await fetch(`/api/admin/users/${id}`, { method: 'DELETE' });
    const json = await res.json();
    setBusy(false);
    if (!res.ok || !json.ok) { setError(json.error || 'Failed to delete'); return; }
    router.refresh();
  }

  return (
    <div className="space-y-6">
      <div className="card p-4">
        <h2 className="mb-3 text-sm font-semibold text-gray-900">Add a new user</h2>
        <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
          <div>
            <label className="label">Name</label>
            <input className="input" value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div>
            <label className="label">Email</label>
            <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div>
            <label className="label">Temporary password</label>
            <input
              className="input"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="At least 8 characters"
            />
          </div>
          <div>
            <label className="label">Role</label>
            <select
              className="input"
              value={role}
              onChange={(e) => setRole(e.target.value as 'ADMIN' | 'EMPLOYEE')}
            >
              <option value="EMPLOYEE">Employee</option>
              <option value="ADMIN">Admin</option>
            </select>
          </div>
        </div>
        <div className="mt-4 flex justify-end">
          <Button onClick={addUser} disabled={busy || !name || !email || password.length < 8}>
            Create user
          </Button>
        </div>
      </div>

      {error ? (
        <div className="rounded-md bg-red-50 p-3 text-sm text-red-700">{error}</div>
      ) : null}

      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-500">
            <tr>
              <th className="px-4 py-3">Name</th>
              <th className="px-4 py-3">Email</th>
              <th className="px-4 py-3">Role</th>
              <th className="px-4 py-3">Joined</th>
              <th className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {initial.map((u) => (
              <tr key={u.id}>
                <td className="px-4 py-3 font-medium text-gray-900">{u.name}</td>
                <td className="px-4 py-3 text-gray-600">{u.email}</td>
                <td className="px-4 py-3">
                  <select
                    className="input h-8 py-0 text-xs"
                    value={u.role}
                    onChange={(e) => changeRole(u.id, e.target.value as 'ADMIN' | 'EMPLOYEE')}
                    disabled={busy || u.id === currentUserId}
                  >
                    <option value="EMPLOYEE">Employee</option>
                    <option value="ADMIN">Admin</option>
                  </select>
                </td>
                <td className="px-4 py-3 text-gray-500">
                  {new Date(u.createdAt).toLocaleDateString()}
                </td>
                <td className="px-4 py-3 text-right">
                  {u.id === currentUserId ? (
                    <span className="text-xs text-gray-400">You</span>
                  ) : (
                    <Button size="sm" variant="danger" onClick={() => removeUser(u.id)} disabled={busy}>
                      Delete
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
