import React from 'react';
import { Box, Typography, IconButton } from '@mui/material';
import { Delete as DeleteIcon, DragIndicator as DragIndicatorIcon } from '@mui/icons-material';
import { useDroppable } from '@dnd-kit/core';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface WidgetGroupProps {
  title: string;
  children: React.ReactNode;
  gridColumn?: string;
  groupId?: string;
  sortableId?: string;
  editMode?: boolean;
  onDelete?: () => void;
}

function WidgetGroup({ title, children, groupId, sortableId, editMode, onDelete }: WidgetGroupProps) {
  const { setNodeRef: setDropRef, isOver } = useDroppable({
    id: groupId ? `group-${groupId}` : 'group-default',
    disabled: !editMode,
  });

  const {
    setNodeRef: setSortableRef,
    attributes,
    listeners,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: sortableId ?? '',
    disabled: !editMode || !sortableId,
  });

  // Count non-null children to hide empty groups
  const validChildren = React.Children.toArray(children).filter(Boolean);

  if (validChildren.length === 0 && !editMode) return null;

  const sortableStyle = sortableId ? {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.4 : 1,
    zIndex: isDragging ? 1 : undefined,
  } : {};

  return (
    <Box
      ref={setSortableRef}
      style={sortableStyle}
      sx={{
        position: 'relative',
        borderRadius: 2,
        p: 2.5,
        pt: 3.5,
        gridColumn: '1 / -1',
        bgcolor: isOver && editMode ? 'rgba(25, 118, 210, 0.04)' : 'rgba(0, 0, 0, 0.02)',
        border: '1px solid',
        borderColor: isOver && editMode ? 'primary.light' : 'rgba(0, 0, 0, 0.04)',
        transition: 'background-color 200ms, border-color 200ms',
        minHeight: editMode ? 60 : undefined,
      }}
    >
      <Box
        ref={setDropRef}
        sx={{
          position: 'absolute',
          top: -9,
          left: 20,
          display: 'flex',
          alignItems: 'center',
          gap: 0.5,
          backgroundColor: 'background.default',
          px: 1.5,
          py: 0.25,
          borderRadius: 1,
        }}
      >
        {editMode && sortableId && (
          <IconButton
            size="small"
            {...attributes}
            {...listeners}
            sx={{ p: 0, mr: 0.25, color: 'text.disabled', cursor: 'grab', '&:active': { cursor: 'grabbing' } }}
          >
            <DragIndicatorIcon sx={{ fontSize: 14 }} />
          </IconButton>
        )}
        <Typography
          sx={{
            fontSize: '0.6875rem',
            color: 'text.secondary',
            fontWeight: 600,
            letterSpacing: '0.06em',
            textTransform: 'uppercase',
          }}
        >
          {title}
        </Typography>
        {editMode && onDelete && (
          <IconButton
            size="small"
            onClick={onDelete}
            sx={{ p: 0, ml: 0.5, color: 'text.secondary', '&:hover': { color: 'error.main' } }}
          >
            <DeleteIcon sx={{ fontSize: 14 }} />
          </IconButton>
        )}
      </Box>
      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
          gap: 2.5,
        }}
      >
        {children}
      </Box>
    </Box>
  );
}

export default WidgetGroup;
