import { css } from "@emotion/react";

const chartContainerCSS = css`
  width: 100%;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  border-radius: var(--global-rounding-medium);
  gap: 2px;
`;

const chartSegmentCSS = css`
  height: 100%;
  flex-shrink: 0;
  flex-grow: 0;
`;

export type SegmentChartProps = {
  /**
   * The height of the chart in pixels.
   * @default 6
   */
  height?: number;
  /**
   * The total value of the chart
   */
  totalValue?: number;
  /**
   * The minimum width of a non-zero segment as a percentage of the chart.
   * @default 0
   */
  minimumSegmentPercentage?: number;
  /**
   * The segments to display in the chart
   */
  segments: {
    /**
     * The name of the segment
     */
    name: string;
    /**
     * The value of the segment
     */
    value: number;
    /**
     * the color for the segment
     */
    color: string;
  }[];
};

export const SegmentChart = ({
  height = 6,
  minimumSegmentPercentage = 0,
  segments,
  totalValue: _totalValue,
}: SegmentChartProps) => {
  // if the total value is not provided, we calculate it from the segments
  // this is useful for cases where the total value is not known ahead of time
  const totalValue =
    _totalValue ?? segments.reduce((acc, segment) => acc + segment.value, 0);
  const visibleSegments =
    minimumSegmentPercentage > 0
      ? segments.filter((segment) => segment.value > 0)
      : segments;
  // An all-zero breakdown has nothing to draw, and a bar of pure background
  // reads as a rendering failure rather than as an empty total.
  if (!visibleSegments.some((segment) => segment.value > 0)) {
    return null;
  }

  return (
    <div style={{ height: `${height}px` }} css={chartContainerCSS}>
      {visibleSegments.map((segment) => {
        const percentage =
          totalValue > 0 ? (segment.value / totalValue) * 100 : 0;
        const color = segment.color;
        const minimumWidth =
          segment.value > 0 && minimumSegmentPercentage > 0
            ? `${minimumSegmentPercentage}%`
            : undefined;
        return (
          <div
            key={segment.name}
            css={chartSegmentCSS}
            style={{
              width: `${percentage}%`,
              minWidth: minimumWidth,
              flexShrink: minimumWidth == null ? 0 : 1,
              backgroundColor: color,
            }}
          />
        );
      })}
    </div>
  );
};
