/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { differenceInSeconds, parseISO } from "date-fns";
import ky from "ky";
import { useEffect, useState } from "react";
import QRCode from "react-qr-code";

function MonitoringPage() {
  const [sessions, setSessions] = useState<any>([]);
  const [servers, setServers] = useState<any>([]);
  const [pin, setPin] = useState<string>("");

  async function getSessionServers() {
    const response = await ky
      .get(`${import.meta.env.VITE_COORD_URL}/session_servers`)
      .json();

    setServers(response);

    setTimeout(() => {
      getSessionServers();
    }, 1000);
  }

  async function getActiveSessions() {
    const response = await ky
      .get(`${import.meta.env.VITE_COORD_URL}/active_sessions`)
      .json();

    setSessions(response);

    setTimeout(() => {
      getActiveSessions();
    }, 1000);
  }

  async function endSession(activeSessionId: string) {
    await ky
      .post(
        `${
          import.meta.env.VITE_COORD_URL
        }/active_sessions/${activeSessionId}/end`
      )
      .json();
  }

  useEffect(() => {
    getActiveSessions();
    getSessionServers();
  }, []);

  return (
    <div className="min-h-screen text-[#F2F2F2] p-4 flex flex-col">
      {pin === "4499" ? (
        <>
          <div className="flex flex-col gap-2 border-b border-[#22222A] pb-4 text-sm">
            <p>Сервера:</p>
            <div className="grid lg:grid-cols-3 gap-2">
              {servers.length > 0 ? (
                servers.map((server: any) => (
                  <div key={server.id} className="p-4 bg-[#22222A] rounded">
                    <div>
                      {differenceInSeconds(
                        new Date(),
                        parseISO(server.updatedAt)
                      ) >= 10 ? (
                        <p className="flex items-center gap-2">
                          <span className="h-2 w-2 rounded-full bg-red-500"></span>
                          <span>Не в сети</span>
                        </p>
                      ) : (
                        <p className="flex items-center gap-2">
                          <span className="h-2 w-2 rounded-full bg-green-500"></span>
                          <span>В сети</span>
                        </p>
                      )}
                    </div>
                    <p>
                      Локация:{" "}
                      <span className="font-medium">{server.location}</span>
                    </p>
                    <p>
                      Имя сервера:{" "}
                      <span className="font-medium">{server.name}</span>
                    </p>
                    <p>
                      Лимит процессов:{" "}
                      <span className="font-medium">
                        {server.limit_process}
                      </span>
                    </p>
                    <div>
                      <p>
                        CPU: <span className="font-medium">{server.cpu}</span>
                      </p>
                      <p>
                        RAM: <span className="font-medium">{server.ram}</span>
                      </p>
                      {/* <p className="flex space-x-2">
                  <span>GPU: </span>
                  <span className="flex space-x-4">
                    {server.gpu?.map((item: any, index: number) => (
                      <span key={index}>
                        {item} {index === 2 && "°C"}
                      </span>
                    ))}
                  </span>
                </p> */}
                    </div>
                  </div>
                ))
              ) : (
                <p className="opacity-50">Нет запущенных серверов</p>
              )}
            </div>
          </div>

          <div className="mt-4 flex flex-col gap-2 text-sm">
            <p>Запущенные сессии:</p>
            {sessions.length > 0 ? (
              sessions.map((session: any) => (
                <div
                  key={session.id}
                  className="flex flex-wrap gap-4 justify-between items-center p-4 bg-[#22222A] rounded"
                >
                  <div className="flex items-center gap-4">
                    <div className="">
                      <QRCode
                        bgColor="#22222A"
                        fgColor="#F2F2F2"
                        size={128}
                        value={`https://stream.graff.tech/stream/?data=wss://${session.location}.sess.stream.graff.tech/${session.server}/${session.cirrusPort}/`}
                        viewBox={`0 0 128 128`}
                      />
                    </div>
                    <div>
                      <p>
                        Локация:{" "}
                        <span className="font-medium">{session.location}</span>
                      </p>
                      <p>
                        Сервер:{" "}
                        <span className="font-medium">{session.server}</span>
                      </p>
                      <p>
                        Сборка:{" "}
                        <span className="font-medium">{session.title}</span>
                      </p>
                      <p>
                        Порт:{" "}
                        <span className="font-medium">
                          {session.cirrusPort}
                        </span>
                      </p>
                      <p>
                        Пользователи:{" "}
                        <span className="font-medium">
                          {session.connectedPlayersCount || 0}
                        </span>
                      </p>
                      <p>
                        Дата и время запуска:{" "}
                        <span className="font-medium">
                          {new Date(session.createdAt).toLocaleString()}
                        </span>
                      </p>
                    </div>
                  </div>

                  <div className="grid lg:grid-cols-1 grid-cols-2 gap-4 lg:w-auto w-full">
                    <a
                      href={`https://stream.graff.tech/stream/${session.id}`}
                      target="_blank"
                      className="inline-block text-center px-4 py-2 bg-blue-600 hover:bg-blue-500 transition-colors rounded"
                    >
                      Открыть в новом окне
                    </a>
                    <button
                      onClick={() => endSession(session.id)}
                      className="px-4 py-2 bg-red-600 hover:bg-red-500 transition-colors rounded"
                    >
                      Завершить сессию
                    </button>
                  </div>
                </div>
              ))
            ) : (
              <p className="opacity-50">Нет запущенных сессий</p>
            )}
          </div>
        </>
      ) : (
        <input
          autoFocus
          type="password"
          value={pin}
          onChange={(e) => setPin(e.target.value)}
          className="w-fit rounded outline-none px-3 py-2"
        />
      )}
    </div>
  );
}

export default MonitoringPage;
