/**
 * Widget grid container using react-grid-layout
 */

import { Responsive as ResponsiveGridLayout, useContainerWidth } from "react-grid-layout";
import type { ReactNode } from "react";
import type { WidgetPlacement } from "@mosaic/shared";

// Import CSS for react-grid-layout
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";

export interface WidgetGridProps {
  children: ReactNode[];
  layout: WidgetPlacement[];
  onLayoutChange?: (layout: readonly WidgetPlacement[]) => void;
  isEditing?: boolean;
  breakpoints?: Record<string, number>;
  cols?: Record<string, number>;
  rowHeight?: number;
  margin?: [number, number];
  containerPadding?: [number, number];
  className?: string;
}

const DEFAULT_BREAKPOINTS = {
  lg: 1200,
  md: 996,
  sm: 768,
  xs: 480,
  xxs: 0,
};

const DEFAULT_COLS = {
  lg: 4,
  md: 3,
  sm: 2,
  xs: 1,
  xxs: 1,
};

export function WidgetGrid({
  children,
  layout,
  onLayoutChange,
  isEditing = false,
  breakpoints = DEFAULT_BREAKPOINTS,
  cols = DEFAULT_COLS,
  rowHeight = 100,
  margin = [16, 16],
  containerPadding = [16, 16],
  className = "",
}: WidgetGridProps): React.JSX.Element {
  // Use hook to measure container width
  const { width, containerRef, mounted } = useContainerWidth({ measureBeforeMount: true });
  // Convert our WidgetPlacement to react-grid-layout's Layout format
  const rglLayout = layout.map((widget) => {
    const layoutItem: {
      i: string;
      x: number;
      y: number;
      w: number;
      h: number;
      minW: number;
      maxW?: number;
      minH: number;
      maxH?: number;
      static?: boolean;
      isDraggable?: boolean;
      isResizable?: boolean;
    } = {
      i: widget.i,
      x: widget.x,
      y: widget.y,
      w: widget.w,
      h: widget.h,
      minW: widget.minW ?? 1,
      minH: widget.minH ?? 1,
    };

    if (widget.maxW !== undefined) layoutItem.maxW = widget.maxW;
    if (widget.maxH !== undefined) layoutItem.maxH = widget.maxH;
    if (widget.static) layoutItem.static = true;
    if (isEditing && widget.isDraggable !== false) layoutItem.isDraggable = true;
    if (isEditing && widget.isResizable !== false) layoutItem.isResizable = true;

    return layoutItem;
  });

  const handleLayoutChange = (layout: readonly WidgetPlacement[]): void => {
    if (onLayoutChange) {
      onLayoutChange(layout);
    }
  };

  return (
    <div ref={containerRef} style={{ width: "100%" }}>
      {mounted && (
        <ResponsiveGridLayout
          className={`widget-grid ${className}`}
          layouts={{ lg: rglLayout }}
          breakpoints={breakpoints}
          cols={cols}
          rowHeight={rowHeight}
          margin={margin}
          containerPadding={containerPadding}
          onLayoutChange={handleLayoutChange}
          width={width}
        >
          {children.map((child, index) => (
            <div key={layout[index]?.i ?? index}>{child}</div>
          ))}
        </ResponsiveGridLayout>
      )}
    </div>
  );
}
