import React, { useEffect, useRef, forwardRef, useLayoutEffect } from 'react';
import styled from 'styled-components';

import type { MarkerArea } from '@redocly/theme/core/types';

type MarkerProps = {
  marker: MarkerArea;
  registerMarker: (element: HTMLElement) => void;
  removeMarker: (element: HTMLElement) => void;
  dataAttribures?: Record<string, string | boolean | number>;
};

export const Marker = forwardRef<HTMLDivElement, MarkerProps>(
  ({ marker, dataAttribures, registerMarker, removeMarker }, forwardedRef) => {
    const internalRef = useRef<HTMLDivElement | null>(null);

    // Reference should be available before paint
    useLayoutEffect(() => {
      if (!forwardedRef) return;
      if (typeof forwardedRef === 'function') {
        forwardedRef(internalRef.current);
      } else {
        forwardedRef.current = internalRef.current;
      }
    }, [forwardedRef]);

    useEffect(() => {
      const currentElement = internalRef.current;
      if (!currentElement) return;

      registerMarker(currentElement);
      return () => removeMarker(currentElement);
    }, [registerMarker, removeMarker, marker]);

    return (
      <StyledMarker
        data-component-name="Marker/Marker"
        ref={internalRef}
        marker={marker}
        {...(dataAttribures ?? {})}
      />
    );
  },
);

const StyledMarker = styled.div<{ marker: MarkerArea }>`
  position: absolute;
  z-index: -1;
  top: ${({ marker }) => marker.offset}px;
  height: ${({ marker }) => marker.height}px;
  width: 100%;
  left: 0;
`;
