import React, { useState } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout'; // Import responsive grid layout
import 'bootstrap/dist/css/bootstrap.min.css'; // Import Bootstrap CSS
import './App.css'; // Import your custom styles

const ResponsiveGridLayout = WidthProvider(Responsive);

const App = () => {
  const numRows = 6; // Fixed number of desired rows
  const rowHeight = 100; // Height per row
  const maxY = numRows - 1; // Define the maximum allowed y-coordinate for blocks
  const NUM_COLS = 4; // Define the number of columns as a constant

  const [layout, setLayout] = useState({
    lg: [
      { i: 'block-1', x: 0, y: 0, w: 1, h: 1, content: 'Text Block 1' },
      { i: 'block-2', x: 1, y: 0, w: 1, h: 2, content: 'Text Block 2' },
      { i: 'block-3', x: 0, y: 1, w: 2, h: 2, content: 'Text Block 3' },
      { i: 'block-4', x: 2, y: 0, w: 1, h: 3, content: 'Text Block 4' },
    ],
  });

  const [isModalOpen, setModalOpen] = useState(false);
  const [editingBlock, setEditingBlock] = useState(null);
  const [blockContent, setBlockContent] = useState('');

  const handleLayoutChange = (newLayout) => {
    // Prevent blocks from being positioned beyond the maximum y (number of rows)
    const limitedLayout = newLayout.map(block => ({
      ...block,
      y: Math.min(block.y, maxY), // Restrict y-coordinate to maxY
    }));

    setLayout(prevLayout => ({
      ...prevLayout,
      lg: limitedLayout,
    }));
  };

  const openEditModal = (block) => {
    setEditingBlock(block);
    setBlockContent(block.content); // Pre-populate with current block content
    setModalOpen(true);
  };

  const closeEditModal = () => {
    setModalOpen(false);
    setEditingBlock(null);
    setBlockContent('');
  };

  const saveBlockContent = () => {
    if (editingBlock) {
      setLayout(prevLayout => ({
        ...prevLayout,
        lg: prevLayout.lg.map(block =>
          block.i === editingBlock.i ? { ...block, content: blockContent } : block
        ),
      }));
      closeEditModal(); // Close modal after saving changes
    }
  };

  const removeBlock = (id, e) => {
    e.stopPropagation(); // Prevent event propagation
    setLayout(prevLayout => ({
      ...prevLayout,
      lg: prevLayout.lg.filter(block => block.i !== id), // Remove block by ID
    }));
  };

  const addBlock = () => {
    const newBlockId = `block-${layout.lg.length + 1}`; // Generate a unique block ID
    let newPos = { x: 0, y: 0 }; // Start from (0,0) to find an empty space

    // Find the first empty position in the grid
    for (let y = 0; y < numRows; y++) {
      for (let x = 0; x < NUM_COLS; x++) { // Assuming NUM_COLS 
        const found = layout.lg.find(block => block.x === x && block.y === y);
        if (!found) {
          newPos = { x, y }; // If position is empty, set newPos
          break; // Exit inner loop since we found an empty position
        }
      }
      if (newPos.y !== y) break; // Exit outer loop if we found a new position
    }

    // Only add the block if the position is valid and within the defined rows
    if (newPos.y <= maxY) {
      const newBlock = {
        i: newBlockId,
        x: newPos.x,
        y: newPos.y,
        w: 1,
        h: 1,
        content: `New Block ${layout.lg.length + 1}`,
      };

      setLayout(prevLayout => ({
        ...prevLayout,
        lg: [...prevLayout.lg, newBlock], // Append new block to layout
      }));
    }
  };

  return (
    <div className="container-fluid">
      <h1>Tetris-Like Layout Editor</h1>
      <button className="btn btn-primary mb-3" onClick={addBlock}>Add Block</button> {/* Button to Add Block */}
      
      <ResponsiveGridLayout
        className="layout"
        layouts={layout} // Responsive layouts for different screen sizes
        breakpoints={{ lg: 1200 }} // Breakpoints
        cols={{ lg: NUM_COLS }} // Use the constant for columns
        rowHeight={rowHeight} // Fixed height of each row
        onLayoutChange={handleLayoutChange} // Handle layout changes
        isDraggable // Allow dragging
        preventCollision // Prevent overlapping items
        verticalCompact={true} // Enable vertical compacting
        draggableHandle=".drag-handle" // Only allow dragging via drag-handle
        style={{ height: `${numRows * rowHeight}px` }} // Set height based on the number of rows
      >
        {layout.lg.map((block) => (
          <div key={block.i} className="block" data-grid={block}>
            <div className="content-area">
              <div className="button-group">
                <button 
                  className="btn btn-secondary btn-sm me-1" 
                  onClick={() => openEditModal(block)} // Edit button
                >
                  Edit
                </button>
                <button 
                  className="btn btn-danger btn-sm" 
                  onClick={(e) => removeBlock(block.i, e)} // Remove button
                >
                  x
                </button>
              </div>
              <span className="drag-handle" style={{ cursor: 'move' }}>
                ☰ {/* Drag handle indicator */}
              </span>
              <p>{block.content}</p>
            </div>
          </div>
        ))}
      </ResponsiveGridLayout>

      {/* Bootstrap Modal for Editing Block Content */}
      <div className={`modal fade ${isModalOpen ? "show" : ""}`} style={{ display: isModalOpen ? "block" : "none" }} tabIndex="-1" role="dialog">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title">Edit Block Content</h5>
              <button type="button" className="close" onClick={closeEditModal}>
                <span>&times;</span>
              </button>
            </div>
            <div className="modal-body">
              <textarea 
                value={blockContent} 
                onChange={(e) => setBlockContent(e.target.value)} 
                className="form-control"
                rows="4"
              />
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" onClick={closeEditModal}>Close</button>
              <button type="button" className="btn btn-primary" onClick={saveBlockContent}>Save changes</button>
            </div>
          </div>
        </div>
      </div>

      {isModalOpen && <div className="modal-backdrop fade show"></div>}
    </div>
  );
};

export default App;

This code does not prevent the user from adding endless amount of blocks even if they pass the maxY. refactor code to fix this.