import React, { useEffect, useState } from 'react';
import { getUsers, createUser, updateUser, deleteUser } from '../api/userService';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newUser, setNewUser] = useState({ email: '', roles: '' });

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userData = await getUsers();
        setUsers(userData);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  const handleCreateUser = async () => {
    try {
      const createdUser = await createUser(newUser);
      setUsers([...users, createdUser]);
      setNewUser({ email: '', roles: '' });
    } catch (error) {
      setError(error);
    }
  };

  const handleUpdateUser = async (userId, updatedData) => {
    try {
      const updatedUser = await updateUser(userId, updatedData);
      setUsers(users.map((user) => (user.ID === userId ? updatedUser : user)));
    } catch (error) {
      setError(error);
    }
  };

  const handleDeleteUser = async (userId) => {
    try {
      await deleteUser(userId);
      setUsers(users.filter((user) => user.ID !== userId));
    } catch (error) {
      setError(error);
    }
  };

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error loading users: {error.message}</p>;

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map((user) => (
          <li key={user.ID}>
            {user.Email} - {user.Roles.join(', ')}
            <button onClick={() => handleUpdateUser(user.ID, {/* Updated data */})}>Update</button>
            <button onClick={() => handleDeleteUser(user.ID)}>Delete</button>
          </li>
        ))}
      </ul>

      <h3>Add New User</h3>
      <input
        type="email"
        placeholder="Email"
        value={newUser.email}
        onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
      />
      <input
        type="text"
        placeholder="Roles (comma-separated)"
        value={newUser.roles}
        onChange={(e) => setNewUser({ ...newUser, roles: e.target.value.split(',') })}
      />
      <button onClick={handleCreateUser}>Create User</button>
    </div>
  );
};

export default UserList;
