import { keyframes } from "@emotion/core";
import styled from "@emotion/styled";
import { observer } from "mobx-react";
import * as React from "react";
import { useEffect, useState } from "react";
import { generateRandomColor } from "../../../shared/utils/utils";
import { CurrentUser_me } from "../../graphql/generated/types";
import { SlideshowStore } from "../../platform/SlideshowStore";

type Props = {
  mouseKey: string;
  user: CurrentUser_me;
  store: SlideshowStore;
  container: React.RefObject<HTMLDivElement>;
};

function MouseClick(props: Props) {
  const mouseClick = props.store.mouseClicks.get(props.mouseKey)!;

  const [animate, setAnimate] = useState(mouseClick.timestamp ? true : false);
  const [x, setX] = useState(mouseClick.x);
  const [y, setY] = useState(mouseClick.y);

  useEffect(() => {
    if (mouseClick.timestamp) {
      setAnimate(true);
      setX(mouseClick.x);
      setY(mouseClick.y);
    }
  }, [mouseClick.timestamp, mouseClick.x, mouseClick.y]);

  const foundUser = props.user.team.users.find(
    (user) => user.id === mouseClick.userId
  )!;

  return (
    <AnimatedClick
      color={generateRandomColor(foundUser.id)}
      top={y}
      left={x}
      animated={animate}
      onAnimationStart={() => setAnimate(true)}
      onAnimationEnd={() => setAnimate(false)}
    />
  );
}

export default observer(MouseClick);

const getClickKeyframe = () => {
  return keyframes`
    0% {
      opacity: 1;
      width:0.2em;
      height:0.2em;
      margin:-0.1em;
      border-width:0.2em;
    }
    100% {
      opacity:0;
      width:8em;
      height:8em;
      margin:-4em;
      border-width:0.03em;
    }
  `;
};

const AnimatedClick = styled.div<{
  top: number;
  left: number;
  animated: boolean;
  color: string;
}>`
  position: absolute;
  height: 50px;
  width: 50px;
  background-color: ${(props) => props.color};
  top: ${(props) => props.top}px;
  left: ${(props) => props.left}px;
  ${(props) => !props.animated && "display: none;"}
  box-sizing: border-box;
  border-color: #ffffff;
  border-radius: 50%;
  animation: ${getClickKeyframe()} 0.3s ease-out;
  z-index: 99999;
`;
