import { Col, List, Space, Typography } from "antd";
import { useTranslation } from "react-i18next";

const CardColorLegend = ({ bodyshop }) => {
  const { t } = useTranslation();
  const data = bodyshop.ssbuckets.map((bucket) => {
    let color = { r: 255, g: 255, b: 255, a: 1 }; // Default to white with full opacity
    if (bucket.color) {
      color = bucket.color;
      if (bucket.color.rgb) {
        color = { ...bucket.color.rgb, a: bucket.color.a || 1 };
      }
    }
    return {
      label: bucket.label,
      color
    };
  });

  const getBackgroundColor = (color) => {
    // Return dynamic color if valid, otherwise use fallback
    return color && color.r !== undefined && color.g !== undefined && color.b !== undefined
      ? `rgba(${color.r},${color.g},${color.b},${color.a || 1})`
      : "var(--legend-bg-fallback)";
  };

  return (
    <Col>
      <Typography>{t("production.labels.legend")}</Typography>
      <List
        grid={{
          gutter: 16
        }}
        dataSource={data}
        renderItem={(item) => (
          <List.Item>
            <Space>
              <div
                style={{
                  width: "1.5rem",
                  aspectRatio: "1/1",
                  backgroundColor: getBackgroundColor(item.color)
                }}
              ></div>
              <div>{item.label}</div>
            </Space>
          </List.Item>
        )}
      />
    </Col>
  );
};

export default CardColorLegend;
