import { View, Image } from "@tarojs/components";
import { FC } from "@tarojs/taro";
import {
  CSSProperties,
  memo,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { requestAnimationFrame } from "@tarojs/runtime";
import classNames from "classnames";
import "./index.scss";

export interface RoundItemProps {
  id: number;
  angle: number;
  bigR: number;
  minR: number;
  isActive: boolean;
  isNear: boolean;
}

const IMG_BASE_URL = "https://houseoss.4dkankan.com/project/wx-csbwg-public";

export const RoundItem: FC<RoundItemProps> = memo(
  ({ id, angle, bigR, minR, isActive, isNear }) => {
    const [curAngle, setCurAngle] = useState(angle);
    const [actImgLoaded, setActImgLoaded] = useState(false);
    const _angle = useRef(angle);
    const inited = useRef(false);
    const timer = useRef<number | NodeJS.Timeout>();
    const moving = useRef(false);

    const style = useMemo<CSSProperties>(() => {
      const x = bigR * (1 - Math.cos((curAngle * Math.PI) / 180)) - minR;
      const y = bigR * (1 - Math.sin((curAngle * Math.PI) / 180)) - minR;
      let scale = 0.5;

      if (isActive) {
        scale = 1;
      } else if (isNear) {
        scale = 0.6;
      }

      return {
        top: y + "px",
        right: x + "px",
        transform: `scale(${scale})`,
      };
    }, [curAngle, bigR, isActive, isNear]);

    useEffect(() => {
      if (inited.current) {
        moving.current = true;
        setActImgLoaded(false);
        move();
      }

      inited.current = true;
    }, [angle]);

    const move = () => {
      const offset = _angle.current - angle;
      _angle.current = _angle.current + (offset > 0 ? -1 : 1);

      setCurAngle(_angle.current);
      timer.current = requestAnimationFrame(move);

      if (offset === 0) {
        cancelAnimationFrame(timer.current as number);
        _angle.current = angle;
        moving.current = false;
      }
    };

    return (
      <View
        className={classNames("round-item", {
          "is-active": isActive,
          "is-near": isNear,
        })}
        style={style}
      >
        <Image
          className={classNames("round-item__img", {
            "fade-out": isActive,
          })}
          mode="aspectFit"
          src={`${IMG_BASE_URL}/line-sights/${id}.png`}
        />

        {isActive && (
          <Image
            className={classNames(
              "round-item__img",
              actImgLoaded ? "active" : "hide"
            )}
            mode="aspectFit"
            src={`${IMG_BASE_URL}/sights/${id}.png`}
            onLoad={() => setActImgLoaded(true)}
          />
        )}
      </View>
    );
  }
);
