import { Progress } from "antd";
import { calculateRoomTime, useTimeline } from "../lib/Connection";
import { useUpdateAfterDelay } from "../util/hooks";

const NextShot = () => {
  const timeline = useTimeline();

  useUpdateAfterDelay(1000);

  if (!timeline) {
    throw new TypeError("NextShot without timeline");
  }

  let remainingTime = 0;
  let remainingPercentage = 0;

  const currentRoomTime = calculateRoomTime();

  const nextItem = timeline.itemAfterTime(currentRoomTime, "shot");

  if (nextItem) {
    const prevShotRoomTime =
      (timeline.itemBeforeTime(currentRoomTime, "shot")?.timestamp || 0) * 1000;
    const nextShotRoomTime = nextItem?.timestamp * 1000;
    const totalRoomTimeBetweenShots = nextShotRoomTime - prevShotRoomTime;
    const roomTimeSinceLastShot = currentRoomTime - prevShotRoomTime;

    remainingTime = Math.round((nextShotRoomTime - currentRoomTime) / 1000);
    remainingPercentage =
      100 - (roomTimeSinceLastShot / totalRoomTimeBetweenShots) * 100;
  }

  return (
    <>
      <h1>Tijd tot volgende shot:</h1>
      <Progress
        type="circle"
        percent={remainingPercentage}
        format={() => `${remainingTime} sec.`}
        strokeColor={"#304ba3"}
        strokeWidth={10}
        status="normal"
      />
    </>
  );
};

export default NextShot;
