import React from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";

interface LegendStyleConfig {
  layerName: string;
  layerId: string;
  property: string;
  colors: string[];
  type: string;
  dimensions: number[];
  breaks: number[];
  labels?: string[];
  columns?: number;
  itemsPerColumn?: number;
}
const StyleLegend: React.FC<LegendStyleConfig> = ({
  layerName,
  layerId,
  property,
  colors,
  type,
  dimensions,
  breaks,
  labels,
  columns = 1,
  itemsPerColumn,
}) => {
  const itemCount = Math.min(colors.length, dimensions.length, Math.max(0, breaks.length - 1));
  return (
    <Box
      key={layerId}
      className="bg-white p-3 max-w-xs opacity-95 transition-opacity duration-300 hover:opacity-100"
      sx={{ borderRadius: 1 }}
    >
      <Typography variant="subtitle2" gutterBottom>
        {layerName} - {property}
      </Typography>
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns:
            itemsPerColumn && itemsPerColumn > 0
              ? undefined
              : `repeat(${Math.max(1, columns)}, minmax(0, 1fr))`,
          gridTemplateRows:
            itemsPerColumn && itemsPerColumn > 0
              ? `repeat(${itemsPerColumn}, minmax(0, auto))`
              : undefined,
          gridAutoFlow:
            itemsPerColumn && itemsPerColumn > 0 ? "column" : undefined,
          columnGap: 1.5,
          rowGap: 0.5,
        }}
      >
        {Array.from({ length: itemCount }, (_, index) => {
          const color = colors[index];
          const dimension = dimensions[index];
          if (index + 1 < breaks.length) {
            const prevValue = breaks[index];
            const currentValue = breaks[index + 1];
            return (
              <Box key={index} className="flex items-center gap-2">
                <Box
                  sx={
                    type === "point"
                      ? {
                          width: dimension,
                          height: dimension,
                          borderRadius: "50%",
                          backgroundColor: color,
                        }
                      : {
                          width: 16,
                          height: dimension,
                          backgroundColor: color,
                          border: `1px solid ${color}`,
                        }
                  }
                />
                <Typography variant="caption" className="text-xs">
                  {labels?.[index] ??
                    `${prevValue?.toFixed(1)} - ${currentValue?.toFixed(1)}`}
                </Typography>
              </Box>
            );
          }

          return null;
        })}
      </Box>
    </Box>
  );
};

export default StyleLegend;
export type { LegendStyleConfig };
