'use client';

import { useState } from 'react';

type User = {
  id: number;
  username: string;
  email: string;
  firstName: string | null;
  lastName: string | null;
  role: string;
  createdAt: string;
};

type Props = {
  users: User[];
  currentUserId: string;
};

export default function UserAdminClient({ users: initial, currentUserId }: Props) {
  const [users, setUsers] = useState(initial);
  const [loading, setLoading] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function toggleRole(user: User) {
    const newRole = user.role === 'admin' ? 'user' : 'admin';
    setLoading(user.id);
    setError(null);
    try {
      const res = await fetch(`/api/admin-users/${user.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role: newRole }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.message ?? 'Okänt fel');
      }
      const updated: User = await res.json();
      setUsers((prev) => prev.map((u) => (u.id === updated.id ? { ...u, role: updated.role } : u)));
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(null);
    }
  }

  return (
    <>
      {error && (
        <div className="mb-4 p-3 bg-red-100 text-red-800 rounded">{error}</div>
      )}
      <table className="w-full border-collapse text-sm">
        <thead>
          <tr className="bg-gray-100 text-left">
            <th className="p-2 border">Användarnamn</th>
            <th className="p-2 border">E-post</th>
            <th className="p-2 border">Namn</th>
            <th className="p-2 border">Roll</th>
            <th className="p-2 border">Skapad</th>
            <th className="p-2 border">Åtgärd</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => {
            const isSelf = String(user.id) === currentUserId;
            return (
              <tr key={user.id} className="hover:bg-gray-50">
                <td className="p-2 border font-medium">{user.username}</td>
                <td className="p-2 border">{user.email}</td>
                <td className="p-2 border">
                  {[user.firstName, user.lastName].filter(Boolean).join(' ') || '—'}
                </td>
                <td className="p-2 border">
                  <span
                    className={`px-2 py-0.5 rounded text-xs font-semibold ${
                      user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100 text-gray-700'
                    }`}
                  >
                    {user.role}
                  </span>
                </td>
                <td className="p-2 border text-gray-500">
                  {new Date(user.createdAt).toLocaleDateString('sv-SE')}
                </td>
                <td className="p-2 border">
                  {isSelf ? (
                    <span className="text-gray-400 text-xs">Du själv</span>
                  ) : (
                    <button
                      onClick={() => toggleRole(user)}
                      disabled={loading === user.id}
                      className="px-3 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
                    >
                      {loading === user.id
                        ? 'Sparar…'
                        : user.role === 'admin'
                        ? 'Sätt som user'
                        : 'Sätt som admin'}
                    </button>
                  )}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
}
