import React, { useState, useEffect } from 'react';
import { Container, Table, Button, Card, Modal, Form, Alert } from 'react-bootstrap';
import { FaUserPlus, FaEdit, FaTrash } from 'react-icons/fa';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [currentUserRole, setCurrentUserRole] = useState(''); // Store current logged in user's role
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    role: 'guest'
  });

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

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await api.get('/users');
      setUsers(response.data);
      setError(null);
    } catch (err) {
      console.error('Error fetching users:', err);
      setError('Failed to load users. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const getCurrentUserRole = async () => {
    try {
      // Get current user info from the JWT token
      const token = localStorage.getItem('token');
      if (token) {
        const payload = JSON.parse(atob(token.split('.')[1]));
        setCurrentUserRole(payload.role);
      }
    } catch (err) {
      console.error('Error getting current user role:', err);
    }
  };

  const handleShowModal = (user = null) => {
    if (user) {
      setCurrentUser(user);
      setFormData({
        username: user.username,
        email: user.email,
        password: '',
        role: user.role
      });
    } else {
      setCurrentUser(null);
      setFormData({
        username: '',
        email: '',
        password: '',
        role: 'guest'
      });
    }
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setCurrentUser(null);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      // Create a clean version of the data to send
      const dataToSend = {...formData};
      
      // For updates, if password is empty, remove it from the request
      if (currentUser && !dataToSend.password.trim()) {
        delete dataToSend.password;
      }
      
      if (currentUser) {
        // Update existing user
        await api.put(`/users/${currentUser.id}`, dataToSend);
        console.log('Updating user with data:', dataToSend);
      } else {
        // Create new user
        await api.post('/users', dataToSend);
      }
      
      fetchUsers();
      handleCloseModal();
      setError(null);
    } catch (err) {
      console.error('Error saving user:', err);
      setError(err.response?.data?.message || 'Failed to save user.');
    }
  };

  const handleDeleteUser = async (userId) => {
    if (window.confirm('Are you sure you want to delete this user?')) {
      try {
        await api.delete(`/users/${userId}`);
        setUsers(users.filter(user => user.id !== userId));
      } catch (err) {
        console.error('Error deleting user:', err);
        setError('Failed to delete user.');
      }
    }
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString();
  };

  if (loading) return <LoadingSpinner />;

  return (
    <Container>
      <h1 className="mb-4">User Management</h1>
      
      {error && <Alert variant="danger">{error}</Alert>}
      
      <Card className="shadow-sm mb-4">
        <Card.Header className="d-flex justify-content-between align-items-center">
          <h4 className="mb-0">All Users</h4>
          <Button variant="primary" onClick={() => handleShowModal()}>
            <FaUserPlus className="me-2" />
            Add New User
          </Button>
        </Card.Header>
        <Card.Body>
          {users.length === 0 ? (
            <p className="text-center py-4">No users found.</p>
          ) : (
            <Table responsive striped bordered hover>
              <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>
                      <span className={`badge bg-${user.role === 'super_admin' ? 'danger' : user.role === 'admin' ? 'primary' : 'secondary'}`}>
                        {user.role}
                      </span>
                    </td>
                    <td>{formatDate(user.created_at)}</td>
                    <td>
                      <Button 
                        variant="outline-secondary" 
                        size="sm" 
                        className="me-2"
                        onClick={() => handleShowModal(user)}
                      >
                        <FaEdit />
                      </Button>
                      <Button 
                        variant="outline-danger" 
                        size="sm"
                        onClick={() => handleDeleteUser(user.id)}
                      >
                        <FaTrash />
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </Table>
          )}
        </Card.Body>
      </Card>

      {/* User Form Modal */}
      <Modal show={showModal} onHide={handleCloseModal}>
        <Modal.Header closeButton>
          <Modal.Title>
            {currentUser ? 'Edit User' : 'Add New User'}
          </Modal.Title>
        </Modal.Header>
        <Form onSubmit={handleSubmit}>
          <Modal.Body>
            <Form.Group className="mb-3">
              <Form.Label>Username</Form.Label>
              <Form.Control
                type="text"
                name="username"
                value={formData.username}
                onChange={handleInputChange}
                required
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Label>Email</Form.Label>
              <Form.Control
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Label>
                {currentUser ? 'Password (leave blank to keep current)' : 'Password'}
              </Form.Label>
              <Form.Control
                type="password"
                name="password"
                value={formData.password}
                onChange={handleInputChange}
                required={!currentUser}
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Label>Role</Form.Label>
              <Form.Select
                name="role"
                value={formData.role}
                onChange={handleInputChange}
                disabled={currentUser && currentUserRole !== 'super_admin' && currentUser.role === 'super_admin'}
              >
                <option value="guest">Guest</option>
                <option value="admin">Admin</option>
                {currentUserRole === 'super_admin' && (
                  <option value="super_admin">Super Admin</option>
                )}
              </Form.Select>
              {currentUser && currentUserRole !== 'super_admin' && currentUser.role === 'super_admin' && (
                <Form.Text className="text-danger">
                  Only super admins can change roles of other super admins
                </Form.Text>
              )}
            </Form.Group>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={handleCloseModal}>
              Cancel
            </Button>
            <Button variant="primary" type="submit">
              {currentUser ? 'Update User' : 'Add User'}
            </Button>
          </Modal.Footer>
        </Form>
      </Modal>
    </Container>
  );
};

export default UserManagement;
