/**
 * Admin user detail page.
 *
 * ⚠️ AUTO-GENERATED BY PRISM (GENERATE_ONCE)
 */

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

export default function AdminUserDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [user, setUser] = useState<AdminUser | null>(null);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!id) return;
    adminApi.getUser(Number(id)).then(setUser).catch((e) => setError(e.message));
  }, [id]);

  const handleToggleActive = async () => {
    if (!user) return;
    setBusy(true);
    try {
      const updated = await adminApi.updateUser(user.id, { is_active: !user.is_active });
      setUser(updated);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'An error occurred');
    } finally {
      setBusy(false);
    }
  };

  const handlePromote = async () => {
    if (!user) return;
    setBusy(true);
    try {
      const updated = await adminApi.promoteUser(user.id);
      setUser(updated);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'An error occurred');
    } finally {
      setBusy(false);
    }
  };

  const handleDemote = async () => {
    if (!user) return;
    setBusy(true);
    try {
      const updated = await adminApi.demoteUser(user.id);
      setUser(updated);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'An error occurred');
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async () => {
    if (!user || !confirm('Are you sure you want to delete this user?')) return;
    setBusy(true);
    try {
      await adminApi.deleteUser(user.id);
      navigate('{{ admin_path }}/users');
    } catch (e) {
      setError(e instanceof Error ? e.message : 'An error occurred');
    } finally {
      setBusy(false);
    }
  };

  if (!user) return <p>Loading...</p>;

  const isAdmin = user.roles.includes('admin');

  return (
    <div className="max-w-2xl">
      <h1 className="text-2xl font-bold text-nordic-900 mb-6">User #{user.id}</h1>
      {error && <p className="text-red-600 mb-4">{error}</p>}
      <div className="bg-white rounded-lg border border-nordic-200 p-6 space-y-4">
        <div>
          <span className="text-sm text-nordic-500">{{ username_field | capitalize }}</span>
          <p className="text-nordic-900">{user.{{ username_field }}}</p>
        </div>
        <div>
          <span className="text-sm text-nordic-500">Roles</span>
          <p className="text-nordic-900">{user.roles.join(', ') || 'none'}</p>
        </div>
        <div>
          <span className="text-sm text-nordic-500">Active</span>
          <p className={user.is_active ? 'text-green-600' : 'text-red-500'}>
            {user.is_active ? 'Yes' : 'No'}
          </p>
        </div>
        <div className="flex gap-2 pt-4 border-t border-nordic-200">
          <button
            onClick={handleToggleActive}
            disabled={busy}
            className="px-3 py-1.5 text-sm rounded border border-nordic-300 hover:bg-nordic-50"
          >
            {user.is_active ? 'Deactivate' : 'Activate'}
          </button>
          {isAdmin ? (
            <button
              onClick={handleDemote}
              disabled={busy}
              className="px-3 py-1.5 text-sm rounded border border-yellow-300 text-yellow-700 hover:bg-yellow-50"
            >
              Demote
            </button>
          ) : (
            <button
              onClick={handlePromote}
              disabled={busy}
              className="px-3 py-1.5 text-sm rounded border border-blue-300 text-blue-700 hover:bg-blue-50"
            >
              Promote to Admin
            </button>
          )}
          <button
            onClick={handleDelete}
            disabled={busy}
            className="px-3 py-1.5 text-sm rounded border border-red-300 text-red-700 hover:bg-red-50"
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  );
}
