import { useState, useEffect } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import ServerCard from "../servers/ServerCard.jsx";
import RconDialog, { useRconDialog } from "../servers/RconDialog.jsx";
import Overview from "../overview/Overview.jsx";
import "@mcl/css/server-card.css";
import "@mcl/css/overview.css";
import { useServerInstances } from "@mcl/queries";

export default function Home() {
  const [server, setServer] = useState();
  const [servers, setServers] = useState([]);
  const [rdOpen, rconToggle] = useRconDialog();
  const { isLoading, data: serversData } = useServerInstances();
  const { servers: serverInstances, clusterMetrics } = serversData ?? {};
  useEffect(() => {
    if (!serverInstances) return;
    serverInstances.sort((a, b) => a.name.localeCompare(b.name));
    setServers(serverInstances);
  }, [serverInstances]);

  const openRcon = (s) => () => {
    setServer(s);
    rconToggle();
  };
  return (
    <Box className="home">
      <Overview clusterMetrics={clusterMetrics} />
      {isLoading && (
        <Box display="flex" alignItems="center" justifyContent="center">
          <Typography variant="h4" sx={{ textAlign: "center" }}>
            Loading Server Information...
          </Typography>
        </Box>
      )}
      {!isLoading && servers.length === 0 && (
        <Box display="flex" alignItems="center" justifyContent="center">
          <Typography variant="h4" sx={{ textAlign: "center" }}>
            No servers found!
          </Typography>
        </Box>
      )}
      <Box className="servers">
        {!isLoading &&
          servers.map((s, k) => (
            <ServerCard key={k} server={s} openRcon={openRcon(s.name)} />
          ))}
      </Box>
      <RconDialog
        keepMounted
        open={rdOpen}
        dialogToggle={rconToggle}
        serverName={server}
      />
    </Box>
  );
}
