import React, { useCallback, useRef, useState, useEffect } from 'react';
import { Responsive, Layout, Layouts } from 'react-grid-layout';
import Box from '@mui/material/Box';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

interface DashboardGridProps {
  layouts: Layouts;
  onLayoutChange: (layouts: Layouts) => void;
  children: React.ReactNode;
  isDraggable?: boolean;
  isResizable?: boolean;
}

const DashboardGrid: React.FC<DashboardGridProps> = ({
  layouts,
  onLayoutChange,
  children,
  isDraggable = true,
  isResizable = true,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);

  // Use ResizeObserver to get container width
  useEffect(() => {
    if (!containerRef.current) return;

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setWidth(entry.contentRect.width);
      }
    });

    resizeObserver.observe(containerRef.current);

    // Initial width
    setWidth(containerRef.current.offsetWidth);

    return () => resizeObserver.disconnect();
  }, []);

  const handleLayoutChange = useCallback(
    (currentLayout: Layout[], allLayouts: Layouts) => {
      onLayoutChange(allLayouts);
    },
    [onLayoutChange]
  );

  return (
    <Box
      ref={containerRef}
      sx={{
        width: '100%',
        minHeight: 400,
        '& .react-grid-layout': {
          position: 'relative',
        },
        '& .react-grid-item': {
          transition: 'all 200ms ease',
          transitionProperty: 'left, top',
          '&.cssTransforms': {
            transitionProperty: 'transform',
          },
          '&.react-draggable-dragging': {
            transition: 'none',
            zIndex: 1000,
            opacity: 0.9,
          },
          '&.resizing': {
            transition: 'none',
            zIndex: 1000,
          },
          '&.react-grid-placeholder': {
            background: 'rgba(25, 118, 210, 0.2)',
            borderRadius: '8px',
            border: '2px dashed rgba(25, 118, 210, 0.5)',
            transition: 'none',
          },
        },
        '& .react-resizable-handle': {
          position: 'absolute',
          width: '20px',
          height: '20px',
          '&::after': {
            content: '""',
            position: 'absolute',
            right: '5px',
            bottom: '5px',
            width: '8px',
            height: '8px',
            borderRight: '2px solid rgba(0, 0, 0, 0.3)',
            borderBottom: '2px solid rgba(0, 0, 0, 0.3)',
            borderRadius: '0 0 2px 0',
          },
        },
        '& .react-resizable-handle-se': {
          bottom: 0,
          right: 0,
          cursor: 'se-resize',
        },
        '& .react-resizable-handle-sw': {
          bottom: 0,
          left: 0,
          cursor: 'sw-resize',
        },
        '& .react-resizable-handle-ne': {
          top: 0,
          right: 0,
          cursor: 'ne-resize',
        },
        '& .react-resizable-handle-nw': {
          top: 0,
          left: 0,
          cursor: 'nw-resize',
        },
      }}
    >
      {width > 0 && (
        <Responsive
          className="layout"
          layouts={layouts}
          breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
          cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
          rowHeight={60}
          width={width}
          margin={[16, 16]}
          containerPadding={[0, 0]}
          onLayoutChange={handleLayoutChange}
          isDraggable={isDraggable}
          isResizable={isResizable}
          useCSSTransforms={true}
          compactType="vertical"
          preventCollision={false}
          draggableHandle=".dashboard-widget-header"
        >
          {children}
        </Responsive>
      )}
    </Box>
  );
};

export default DashboardGrid;
