// ColumnChartContent.tsx
// This component renders the grouped/stacked columns for a column chart, using StackedSegment for each x-axis category.
// It handles the layout and mapping of data series to visual columns.

import React, { memo, useMemo } from 'react';
import { G } from 'react-native-svg';
import { deepCompareValue } from '../../../utils/helpers';
import useScaleBandX from '../shared/hooks/useScaleBandX';
import type { DataValue, Series, XAxisConfig, YAxisConfig } from '../types';
import StackedSegment from './StackedSegment';

interface ColumnChartContentProps {
  coordinates: { yStart: number; yEnd: number; xStart: number; xEnd: number };
  data: Array<Series<Array<DataValue>>>;
  yAxisConfig: Omit<YAxisConfig, 'minValue'>;
  xAxisConfig: XAxisConfig;
  /**
   * Called when a bar (column segment) is pressed.
   */
  onBarPress?: (info: {
    value: number | undefined;
    xLabel: string;
    seriesLabel: string;
    seriesIndex: number;
    xIndex: number;
  }) => void;
  /**
   * A function that maps series labels to colors.
   */
  colorScale?: (label: string) => string | undefined;
}

/**
 * Renders the grouped/stacked columns for a column chart.
 * For each x-axis category, renders a StackedSegment with the values from all series.
 * Handles layout and mapping of data to visual columns.
 */
const ColumnChartContent = ({
  coordinates,
  data,
  yAxisConfig,
  xAxisConfig,
  onBarPress,
  colorScale,
}: ColumnChartContentProps) => {
  const { yStart, yEnd, xStart, xEnd } = coordinates;

  const xLabels = xAxisConfig.labels ?? [];

  // Render columns (fixed width, center of group/column aligns to grid)
  const scaleX = useScaleBandX({
    labels: xAxisConfig.labels ?? [],
    xStart,
    xEnd,
  });
  const columns = useMemo(() => {
    if (data.length === 0) {
      return null;
    }
    return xLabels.flatMap((_, xIdx) => {
      const stackedData = data.map((series) => {
        return series.data[xIdx] ?? undefined;
      });

      const x = scaleX(xLabels[xIdx]);
      if (!x) {
        return null; // Handle case where x is undefined
      }
      const seriesLabels = data.map((series) => series.label);
      const xLabel = xLabels[xIdx];
      return (
        <StackedSegment
          key={`${xLabel}-series`}
          stackedData={stackedData}
          xLabel={xLabel}
          yAxisConfig={yAxisConfig}
          coordinates={coordinates}
          xCenter={x + scaleX.bandwidth() / 2}
          seriesLabels={seriesLabels}
          xIndex={xIdx}
          onBarPress={onBarPress}
          colorScale={colorScale}
        />
      );
    });
  }, [
    xLabels,
    data,
    xStart,
    yStart,
    xEnd,
    yEnd,
    onBarPress,
    yAxisConfig,
    colorScale,
  ]);

  return <G testID="column-chart-content">{columns}</G>;
};
export default memo(ColumnChartContent, deepCompareValue);
