import React, { useEffect, useLayoutEffect, useRef } from 'react';
import Loading from '../Loading';
import { ModelWrap } from './ModelWrap';
import { MediaBasicProps } from '.';
import { jsonProxy2, revokeJsonProxy } from '@/utils/constants';

const Model: React.FC<MediaBasicProps> = ({
  media,
  mediaVisible,
  isDetail,
  cssStyle = '',
}) => {
  const contentElement = useRef<HTMLElement>();
  const containerElement = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => {
    if (isDetail) {
      return;
    }
    const mv = contentElement.current;
    if (!mv) {
      return;
    }
    const { shadowRoot } = mv;
    if (!shadowRoot) {
      return;
    }
    const button = shadowRoot.querySelectorAll(
      '#default-poster',
    )[0] as HTMLElement;
    button.style.background = 'none';

    const el = mv.parentNode?.parentNode?.parentNode?.parentNode as HTMLElement;
    mv.style.opacity = '0';
    mv.style.width = `${el?.offsetWidth}px`;
    mv.style.height = `${el?.offsetHeight}px`;
    setTimeout(
      () => {
        mv.style.opacity = '1';
      },
      mediaVisible ? 800 : 1300,
    );
  }, [isDetail, mediaVisible]);

  useEffect(() => {
    if (!isDetail) {
      return;
    }
    const mv = contentElement.current;
    if (!mv) {
      return;
    }
    const { shadowRoot } = mv;
    if (!shadowRoot) {
      return;
    }
    const el2 = contentElement.current?.parentNode?.parentNode
      ?.parentNode as HTMLElement;
    mv.style.width = `${el2?.offsetWidth}px`;
    mv.style.height = `${el2?.offsetWidth}px`;
  }, []);

  return (
    <ModelWrap cssStyle={cssStyle}>
      <div className="modelContainer" ref={containerElement}>
        <Loading
          cssStyle={`
          display: none;
        `}
        />
        <model-viewer
          ref={contentElement}
          src={jsonProxy2(revokeJsonProxy(media))}
          ar
          ar-modes="webxr scene-viewer quick-look"
          environment-image="neutral"
          auto-rotate
          camera-controls
          onClick={(e: Event) => {
            e.stopPropagation();
          }}
        />
      </div>
    </ModelWrap>
  );
};

export default Model;
