import { createElement, useEffect, useRef } from 'react';
import { useDelayResetState } from '../../hooks';
import { MousePos } from './YearConfigs';

export function ChartTooltip(props: {
  selected: any;
  tooltip?: React.FC<{ item?: any }>;
  pos: MousePos | null;
  onClose: () => void;
}) {
  const { onClose, selected, tooltip, pos } = props;
  const ref = useRef(false);
  const value = useDelayResetState(selected, 10, 3000);

  useEffect(() => {
    if (value) {
      ref.current = true;
    }
    if (ref.current && !value) {
      ref.current = false;
      onClose();
    }
  }, [onClose, value, selected]);

  return tooltip && value ? (
    <div
      style={{
        padding: '10px',
        position: 'fixed',
        zIndex: 10000,
        left: pos?.x,
        top: pos?.y,
      }}
    >
      {createElement(tooltip, { item: value })}
    </div>
  ) : (
    <></>
  );
}
