/**
 * Admin users list page.
 *
 * ⚠️ AUTO-GENERATED BY PRISM (GENERATE_ONCE)
 */

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { adminApi, type AdminUser } from '../../lib/adminApi';

export default function AdminUsers() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState('');
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteStatus, setInviteStatus] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
  const [inviting, setInviting] = useState(false);

  useEffect(() => {
    adminApi
      .listUsers()
      .then((res) => {
        setUsers(res.users);
        setTotal(res.total);
      })
      .catch((err) => setError(err.message));
  }, []);

  const handleInvite = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inviteEmail.trim()) return;
    setInviting(true);
    setInviteStatus(null);
    try {
      const res = await adminApi.inviteUser(inviteEmail.trim());
      setInviteStatus({ type: 'success', message: res.message });
      setInviteEmail('');
    } catch (err) {
      setInviteStatus({ type: 'error', message: err instanceof Error ? err.message : 'Failed to send invite' });
    } finally {
      setInviting(false);
    }
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-nordic-900 mb-6">
        Users <span className="text-nordic-400 font-normal text-lg">({total})</span>
      </h1>

      {/* Invite form */}
      <div className="bg-white rounded-lg border border-nordic-200 p-4 mb-6">
        <h2 className="text-sm font-medium text-nordic-700 mb-2">Invite user</h2>
        <form onSubmit={handleInvite} className="flex items-center gap-2">
          <input
            type="email"
            value={inviteEmail}
            onChange={(e) => setInviteEmail(e.target.value)}
            placeholder="email@example.com"
            required
            disabled={inviting}
            className="flex-1 px-3 py-1.5 text-sm border border-nordic-200 rounded-md focus:outline-none focus:ring-2 focus:ring-nordic-500 disabled:bg-nordic-50"
          />
          <button
            type="submit"
            disabled={inviting}
            className="px-4 py-1.5 text-sm bg-nordic-600 text-white rounded-md hover:bg-nordic-700 disabled:bg-nordic-300 transition-colors"
          >
            {inviting ? 'Sending...' : 'Invite'}
          </button>
        </form>
        {inviteStatus && (
          <p className={`mt-2 text-sm ${inviteStatus.type === 'success' ? 'text-green-600' : 'text-red-600'}`}>
            {inviteStatus.message}
          </p>
        )}
      </div>

      {error && <p className="text-red-600 mb-4">{error}</p>}
      <div className="bg-white rounded-lg border border-nordic-200 overflow-hidden">
        <table className="min-w-full divide-y divide-nordic-200">
          <thead className="bg-nordic-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-medium text-nordic-500 uppercase">ID</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-nordic-500 uppercase">{{ username_field | capitalize }}</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-nordic-500 uppercase">Roles</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-nordic-500 uppercase">Active</th>
              <th className="px-4 py-3"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-nordic-100">
            {users.map((u) => (
              <tr key={u.id}>
                <td className="px-4 py-3 text-sm text-nordic-700">{u.id}</td>
                <td className="px-4 py-3 text-sm text-nordic-900">{u.{{ username_field }}}</td>
                <td className="px-4 py-3 text-sm text-nordic-600">{u.roles.join(', ')}</td>
                <td className="px-4 py-3 text-sm">
                  <span className={u.is_active ? 'text-green-600' : 'text-red-500'}>
                    {u.is_active ? 'Yes' : 'No'}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm text-right">
                  <Link to={`{{ admin_path }}/users/${u.id}`} className="text-nordic-600 hover:text-nordic-900">
                    View
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
