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

export default function Home() {
  const clusterMetrics = { cpu: 0, memory: 0 };
  const [server, setServer] = useState();
  const [servers, setServers] = useState([]);
  const [rdOpen, rconToggle] = useRconDialog();
  const { isLoading, data: serversData } = useServerInstances();
  const serverInstances = 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 open={rdOpen} dialogToggle={rconToggle} serverName={server} />
      <Button
        component={Link}
        to="/mcl/create"
        color="primary"
        variant="contained"
        sx={{
          position: "absolute",
          bottom: 16,
          right: 16,
          padding: "1rem",
          borderRadius: "100%",
          height: "4rem",
          width: "4rem",
        }}
      >
        <SpeedDialIcon />
      </Button>
    </Box>
  );
}
