import React from 'react';
import { Platform } from 'react-native';
import { ForeignObject, G } from 'react-native-svg';
import { useTheme } from '../../../theme';
import Box from '../../Box';
import type { AxisCoordinates, XAxisConfig } from '../types';
import AxisLabel from './AxisLabel';
import useScaleBandX from './hooks/useScaleBandX';

export type XAxisProps = {
  // X axis config
  xAxisConfig: XAxisConfig;
  // X axis start offset
  coordinates: AxisCoordinates;
};

const XAxis = ({ xAxisConfig, coordinates }: XAxisProps) => {
  const { xStart, xEnd, yEnd } = coordinates;
  const { labels = [] } = xAxisConfig;
  const theme = useTheme();
  const {
    space: { xAxisGridTextMarginTop },
    sizes: { xAxisDefaultTextHeight },
  } = theme.__hd__.chart;

  const scaleX = useScaleBandX({ labels, xStart, xEnd });

  return (
    <G>
      {labels.map((label) => (
        <G key={label}>
          {/*
            Cross-platform Y-axis label rendering:
            - On web: Use ForeignObject to allow HTML/CSS styling and ellipsis with Typography.Label.
              The x position is set to xStart - yAxisDefaultTextWidth to right-align the label box.
            - On native: Use Box with absolute positioning and Typography.Label for compatibility.
              The transform centers the label vertically.
          */}
          {Platform.OS === 'web' ? (
            <ForeignObject
              x={(scaleX(label) ?? 0) + scaleX.bandwidth() / 2}
              y={yEnd + xAxisGridTextMarginTop}
              width={scaleX.bandwidth()}
              height={xAxisDefaultTextHeight}
            >
              <AxisLabel label={label} numberOfLines={2} textAlign="center" />
            </ForeignObject>
          ) : (
            <Box
              testID={`x-axis-label-${label}-container`}
              style={{
                width: scaleX.bandwidth(),
                maxHeight: xAxisDefaultTextHeight,
                position: 'absolute',
                left: scaleX(label) ?? 0 + scaleX.bandwidth() / 2,
                top: yEnd + xAxisGridTextMarginTop,
              }}
              alignItems="center"
            >
              <AxisLabel label={label} numberOfLines={2} textAlign="center" />
            </Box>
          )}
        </G>
      ))}
    </G>
  );
};

export default XAxis;
