/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
import { differenceInMilliseconds, isAfter, parseISO } from "date-fns";
import ky from "ky";
import { useEffect, useState } from "react";
import Countdown from "react-countdown";
import { useLocation, useNavigate, useParams } from "react-router-dom";

function ScheduledPage() {
  const params = useParams();
  const { search } = useLocation();
  const navigate = useNavigate();
  const [countdownSeconds, setCountdownSeconds] = useState<number>();

  async function connect() {
    try {
      const result: any = await ky
        .get(
          `${import.meta.env.VITE_CRM_API_URL}/scheduled_sessions/${
            params.sessionId
          }`
        )
        .json();

      if (isAfter(parseISO(result.startAt), new Date())) {
        const diffMs = differenceInMilliseconds(
          parseISO(result.startAt),
          new Date()
        );

        setCountdownSeconds(diffMs);
        return;
      }

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

  useEffect(() => {
    connect();
  }, []);

  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 + 15000}
              onComplete={() => window.location.reload()}
            />
          </p>
        </div>
      )}
    </div>
  );
}

export default ScheduledPage;
