/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
import ky from "ky";
import { useEffect, useState } from "react";
import Countdown from "react-countdown";
import { useNavigate, useSearchParams } from "react-router-dom";

function ScheduledPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [countdownSeconds, setCountdownSeconds] = useState<number>();

  async function connect() {
    const userInviteKey = searchParams.get("userInviteKey");

    try {
      const result: any = await ky
        .get(
          `${
            import.meta.env.VITE_COORD_URL
          }/active_sessions/scheduled?userInviteKey=${userInviteKey}`
        )
        .json();

      if (!result.id) {
        setCountdownSeconds(result.countdownSeconds);
        return;
      }

      navigate(`/stream/${result.id}`);
    } catch (error) {
      if (error instanceof Error) {
        console.log(error.message);
      }
    }
  }

  useEffect(() => {
    if (searchParams.get("userInviteKey")) {
      // console.log(searchParams.get("userInviteKey"));

      connect();
    } else {
      navigate("/");
    }
  }, []);

  return (
    <div className="min-h-screen p-8 text-[#F2F2F2] flex flex-col justify-center items-center">
      {countdownSeconds && (
        <div className="space-y-4 w-[340px]">
          <p className="text-2xl font-gilroy">Сеанс начнется через:</p>
          <p className="text-6xl font-gilroy">
            <Countdown
              date={Date.now() + countdownSeconds + 10000}
              onComplete={() => window.location.reload()}
            />
          </p>
        </div>
      )}
    </div>
  );
}

export default ScheduledPage;
