/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useRef, useState } from "react";
import useModalStore from "../../stores/useModalStore";
import ky from "ky";
import { useParams } from "react-router-dom";

function AFKTimerModal() {
  const setModal = useModalStore((state) => state.setModal);
  const [afkTimer, setAfkTimer] = useState<number>(60);
  const afkTimerRef = useRef<number>();
  afkTimerRef.current = afkTimer;
  const params = useParams();

  async function endSession() {
    await ky.post(
      `${import.meta.env.VITE_COORD_URL}/active_sessions/${params.id}/end`
    );
  }

  async function checkAFK() {
    if (afkTimerRef.current && afkTimerRef.current <= 1) {
      await endSession();
      window.location.reload();
      return;
    }

    setAfkTimer((prev) => prev - 1);
  }

  useEffect(() => {
    const interval = setInterval(() => {
      checkAFK();
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  return (
    <div className="relative lg:p-10 p-6 bg-[#131317] rounded shadow-lg w-[320px]">
      <div className="flex flex-col gap-4">
        <p className="text-2xl">AFK Check</p>
        <p>Session will end in {afkTimer} seconds</p>
        <button
          onClick={() => setModal(null)}
          className="px-3 py-2 bg-blue-600 hover:bg-blue-700 transition-colors rounded"
        >
          I'm here
        </button>
      </div>
    </div>
  );
}

export default AFKTimerModal;
