import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './admin.css'; // Ensure admin.css is imported for styling

const UsersPage = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const user = [
    {username: 'johndoe', email: 'jogndoe@gmail.com', role: 'admin', createdAt: '2023-10-01T12:00:00Z'},
    {username: 'janedoe', email: 'janedoe12@gmail.com', role: 'user', createdAt: '2023-10-02T12:00:00Z'},
    {username: 'alice', email: 'alice33@gmail.com', role: 'agent', createdAt: '2023-10-03T12:00:00Z'},
  ]
  // State for modal and form
  const [showModal, setShowModal] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [currentUser, setCurrentUser] = useState(null); // User being edited
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    role: 'user', // Default role
  });

  const BACKEND_API_URL = process.env.REACT_APP_BACKEND_API_URL || 'http://localhost:5000';

  const fetchUsers = async () => {
    setLoading(true);
    setError(null);
    try {
    //   const response = await axios.get(`${BACKEND_API_URL}/api/admin/users`);
      setUsers(user);
    } catch (err) {
      console.error('Error fetching users:', err);
      setError('Failed to fetch users. Is backend running? ' + (err.response?.data?.msg || err.message));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // Form input change handler
  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  // Open Add User Modal
  const handleAddUserClick = () => {
    setIsEditing(false);
    setCurrentUser(null);
    setFormData({ username: '', email: '', password: '', role: 'user' });
    setShowModal(true);
  };

  // Open Edit User Modal
  const handleEditUserClick = (user) => {
    setIsEditing(true);
    setCurrentUser(user);
    setFormData({
      username: user.username,
      email: user.email,
      password: '', // Never pre-fill password for security
      role: user.role,
    });
    setShowModal(true);
  };

  // Handle form submission (Create or Update)
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    try {
      if (isEditing) {
        // Update User
        const updateData = {
          username: formData.username,
          email: formData.email,
          role: formData.role,
        };
        if (formData.password) { // Only send password if it's updated
          updateData.password = formData.password;
        }
        await axios.put(`${BACKEND_API_URL}/api/admin/users/${currentUser._id}`, updateData);
        alert('User updated successfully!');
      } else {
        // Create User
        await axios.post(`${BACKEND_API_URL}/api/admin/users`, formData);
        alert('User created successfully!');
      }
      setShowModal(false);
      fetchUsers(); // Refresh user list
    } catch (err) {
      console.error('Error saving user:', err);
      setError('Failed to save user: ' + (err.response?.data?.msg || err.message));
    }
  };

  // Handle Delete User
  const handleDeleteUser = async (userId) => {
    if (window.confirm('Are you sure you want to delete this user?')) {
      setError(null);
      try {
        await axios.delete(`${BACKEND_API_URL}/api/admin/users/${userId}`);
        alert('User deleted successfully!');
        fetchUsers(); // Refresh user list
      } catch (err) {
        console.error('Error deleting user:', err);
        setError('Failed to delete user: ' + (err.response?.data?.msg || err.message));
      }
    }
  };

  if (loading) return <div className="loading">Loading users...</div>;
  if (error && !showModal) return <div className="error">{error}</div>; // Only show main error if modal is not active

  return (
    <div className="admin-page">
      <h2>User Management</h2>
      <button className="add-button" onClick={handleAddUserClick}>Add New User</button>
      {error && showModal && <div className="error-in-modal">{error}</div>} {/* Show error in modal context */}

      <table className="admin-table">
        <thead>
          <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Created At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {users?.map(user => (
            <tr key={user._id}>
              <td>{user.username}</td>
              <td>{user.email}</td>
              <td>{user.role}</td>
              <td>{new Date(user.createdAt).toLocaleDateString()}</td>
              <td>
                <button className="action-button edit-button" onClick={() => handleEditUserClick(user)}>Edit</button>
                <button className="action-button delete-button" onClick={() => handleDeleteUser(user._id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Modal for Add/Edit User */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <h3>{isEditing ? 'Edit User' : 'Add New User'}</h3>
            {error && !isEditing && <div className="error-in-modal">{error}</div>} {/* Display error for creation attempts */}
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Username:</label>
                <input
                  type="text"
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  required
                />
              </div>
              <div className="form-group">
                <label>Email:</label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  required
                />
              </div>
              <div className="form-group">
                <label>Password: {isEditing && <small>(Leave blank to keep current)</small>}</label>
                <input
                  type="password"
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  required={!isEditing} // Password required only for new users
                />
              </div>
              <div className="form-group">
                <label>Role:</label>
                <select name="role" value={formData.role} onChange={handleChange}>
                  <option value="user">User</option>
                  <option value="agent">Agent</option>
                  <option value="admin">Admin</option>
                </select>
              </div>
              <div className="modal-actions">
                <button type="submit" className="action-button submit-button">{isEditing ? 'Update User' : 'Create User'}</button>
                <button type="button" className="action-button cancel-button" onClick={() => setShowModal(false)}>Cancel</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default UsersPage;