import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './admin.css';

const RoomsPage = () => {
  const [rooms, setRooms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // State for modal and form
  const [showModal, setShowModal] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [currentRoom, setCurrentRoom] = useState(null); // Room being edited
  const [formData, setFormData] = useState({
    roomName: '',
    description: '',
    isPrivate: false,
  });

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

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

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

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

  // Open Add Room Modal
  const handleAddRoomClick = () => {
    setIsEditing(false);
    setCurrentRoom(null);
    setFormData({ roomName: '', description: '', isPrivate: false });
    setShowModal(true);
  };

  // Open Edit Room Modal
  const handleEditRoomClick = (room) => {
    setIsEditing(true);
    setCurrentRoom(room);
    setFormData({
      roomName: room.roomName,
      description: room.description,
      isPrivate: room.isPrivate,
    });
    setShowModal(true);
  };

  // Handle form submission (Create or Update)
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    try {
      if (isEditing) {
        // Update Room
        await axios.put(`${BACKEND_API_URL}/api/admin/rooms/${currentRoom._id}`, formData);
        alert('Room updated successfully!');
      } else {
        // Create Room
        await axios.post(`${BACKEND_API_URL}/api/admin/rooms`, formData);
        alert('Room created successfully!');
      }
      setShowModal(false);
      fetchRooms(); // Refresh room list
    } catch (err) {
      console.error('Error saving room:', err);
      setError('Failed to save room: ' + (err.response?.data?.msg || err.message));
    }
  };

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

  if (loading) return <div className="loading">Loading rooms...</div>;
  if (error && !showModal) return <div className="error">{error}</div>;

  return (
    <div className="admin-page">
      <h2>Room Management</h2>
      <button className="add-button" onClick={handleAddRoomClick}>Add New Room</button>
      {error && showModal && <div className="error-in-modal">{error}</div>}

      <table className="admin-table">
        <thead>
          <tr>
            <th>Room Name</th>
            <th>Description</th>
            <th>Private</th>
            <th>Created By</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {rooms.map(room => (
            <tr key={room._id}>
              <td>{room.roomName}</td>
              <td>{room.description}</td>
              <td>{room.isPrivate ? 'Yes' : 'No'}</td>
              <td>{room.createdBy ? room.createdBy.username : 'N/A'}</td>
              <td>
                <button className="action-button edit-button" onClick={() => handleEditRoomClick(room)}>Edit</button>
                <button className="action-button delete-button" onClick={() => handleDeleteRoom(room._id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* Modal for Add/Edit Room */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <h3>{isEditing ? 'Edit Room' : 'Add New Room'}</h3>
            {error && !isEditing && <div className="error-in-modal">{error}</div>}
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Room Name:</label>
                <input
                  type="text"
                  name="roomName"
                  value={formData.roomName}
                  onChange={handleChange}
                  required
                  disabled={isEditing} 
                />
              </div>
              <div className="form-group">
                <label>Description:</label>
                <input
                  type="text"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                />
              </div>
              <div className="form-group checkbox-group"> {/* Add a class for checkbox styling */}
                <input
                  type="checkbox"
                  name="isPrivate"
                  checked={formData.isPrivate}
                  onChange={handleChange}
                  id="isPrivateCheckbox"
                />
                <label htmlFor="isPrivateCheckbox">Private Room</label>
              </div>
              <div className="modal-actions">
                <button type="submit" className="action-button submit-button">{isEditing ? 'Update Room' : 'Create Room'}</button>
                <button type="button" className="action-button cancel-button" onClick={() => setShowModal(false)}>Cancel</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default RoomsPage;