import React, { useCallback, useState, useMemo } from 'react';
import type { LayoutChangeEvent } from 'react-native';
import { Platform } from 'react-native';
import { ForeignObject, G } from 'react-native-svg';
import Box from '../../Box';
import Typography from '../../Typography';
import type { AxisCoordinates } from '../types';
import { useTheme } from '../../../theme';

type EmptyStateProps = {
  coordinates: AxisCoordinates;
  content: string;
};

const EmptyStateText = ({ content }: { content: string }) => {
  return (
    <Typography.Caption
      fontWeight="semi-bold"
      intent="muted"
      numberOfLines={1}
      ellipsizeMode="tail"
      style={{ textAlign: 'center' }}
    >
      {content}
    </Typography.Caption>
  );
};

const EmptyState = ({ content, coordinates }: EmptyStateProps) => {
  const [textSize, setTextSize] = useState({ width: 0, height: 0 });
  const { xStart, xEnd, yStart, yEnd } = coordinates;
  const theme = useTheme();
  const {
    sizes: { defaultWebEmptyStateWidth, defaultWebEmptyStateHeight },
  } = theme.__hd__.chart;

  const centerPosition = useMemo(() => {
    const centerX = xStart + (xEnd - xStart) / 2;
    const centerY = yStart + (yEnd - yStart) / 2;
    return { centerX, centerY };
  }, [xStart, xEnd, yStart, yEnd]);

  const onTextLayout = useCallback((event: LayoutChangeEvent) => {
    const { width, height } = event.nativeEvent.layout;
    setTextSize({ width, height });
  }, []);

  return (
    <G>
      {Platform.OS === 'web' ? (
        <ForeignObject
          x={centerPosition.centerX - defaultWebEmptyStateWidth / 2}
          y={centerPosition.centerY - defaultWebEmptyStateHeight / 2}
          width={defaultWebEmptyStateWidth}
          height={defaultWebEmptyStateHeight}
        >
          <Box
            style={{
              width: '100%',
              height: '100%',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <EmptyStateText content={content} />
          </Box>
        </ForeignObject>
      ) : (
        <Box
          onLayout={onTextLayout}
          style={{
            position: 'absolute',
            left: centerPosition.centerX - textSize.width / 2,
            top: centerPosition.centerY - textSize.height / 2,
          }}
        >
          <EmptyStateText content={content} />
        </Box>
      )}
    </G>
  );
};

export default EmptyState;
