/* eslint-disable react-hooks/exhaustive-deps */
import React, { memo, useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
const isPreview = /\/app\/preview\/[0-9]+/.test(top.location.href);

const defaultAnimation = {
  from: {
    opacity: 0
  },
  to: {
    opacity: 1
  },
  config: {
    duration: 600
  }
};

const PageAnimation = ({ children, active, animation = defaultAnimation }) => {
  const { from, to, config } = animation;
  const { duration } = config;
  const [opacity, setOpacity] = useState(1);
  const screenRef = useRef(null);

  useEffect(() => {
    const startStatus = active ? from : to;
    const endStatus = active ? to : from;
    if (endStatus?.opacity != null) {
      screenRef.current &&
        d3
          .select(screenRef.current)
          ?.transition?.()
          .duration(duration)
          .tween('attr.opacity', () => {
            const interpolates = d3.interpolateNumber(startStatus.opacity, endStatus.opacity);
            return (t) => {
              setOpacity(interpolates(t));
            };
          });
    }
  }, [active]);

  return (
    <div
      ref={screenRef}
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100vw',
        backgroundColor: isPreview ? 'rgb(24, 27, 36)' : 'none',
        height: '100vh',
        visibility: opacity === 0 ? 'hidden' : 'visible',
        display: opacity === 0 ? 'none' : 'block',
        opacity: opacity === 1 || opacity === 0 ? undefined : opacity
      }}
    >
      {children}
    </div>
  );
};

export default memo(PageAnimation);
