import * as React from 'react';
import { Html } from 'react-konva-utils';

export interface ControlsProps {
  containerRef: React.MutableRefObject<HTMLDivElement>;
  hidden?: boolean;
}
const PADDING_OFFSET = 16;

export const Controls = ({
  containerRef,
  children,
  hidden = false,
}: React.PropsWithChildren<ControlsProps>) => {
  const position = useControlsPosition(containerRef);

  return hidden ? null : (
    <Html
      divProps={{
        style: {
          position: 'fixed',
          top: `${position.top + PADDING_OFFSET}px`,
          left: `${position.left + PADDING_OFFSET}px`,
        },
      }}
      transform={false}
    >
      {children}
    </Html>
  );
};

function useControlsPosition(
  containerRef: React.MutableRefObject<HTMLDivElement>,
) {
  const [position, setPosition] = React.useState({ top: 0, left: 0 });
  const observeRef = React.useRef(
    new ResizeObserver((entries) => {
      const container = entries[0];
      if (container) {
        setPosition({
          top: container.target.getBoundingClientRect().top ?? 0,
          left: container.target.getBoundingClientRect().left ?? 0,
        });
      }
    }),
  );

  React.useEffect(() => {
    if (containerRef.current) {
      observeRef.current.observe(containerRef.current);
    }
    return () => {
      observeRef.current.disconnect();
    };
  }, [containerRef.current]);

  return position;
}
