// @ts-nocheck
import { useState, useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Skeleton from "@mui/material/Skeleton";
import Typography from "@mui/material/Typography";
import RconSocket from "./RconSocket.js";
import "@mcl/css/rcon.css";

function RconLogSkeleton() {
  return (
    <Skeleton
      variant="text"
      width="100%"
      sx={{ backgroundColor: "rgba(255,255,255,.25)" }}
    />
  );
}

export default function RconView(props) {
  const { serverId } = props;
  const logsRef = useRef(0);
  const [cmd, setCmd] = useState("");
  const [logs, setLogs] = useState([]);
  const [rcon, setRcon] = useState();
  const updateCmd = (e) => setCmd(e.target.value);

  const disconnectRcon = () => {
    if (!rcon || typeof rcon.disconnect !== "function") return;
    rcon.disconnect();
  };

  useEffect(
    function () {
      if (!serverId) return;
      const rs = new RconSocket(setLogs, serverId);
      setRcon(rs);
      return disconnectRcon;
    },
    [serverId],
  );

  useEffect(
    () => logsRef.current.scrollTo(0, logsRef.current.scrollHeight),
    [(rcon ?? {}).logs],
  );

  function sendCommand() {
    rcon.send(cmd);
    setCmd("");
  }

  return (
    <Box sx={{ height: "100%", display: "flex", flexWrap: "wrap" }}>
      <Box
        className="rconLogsWrapper"
        ref={logsRef}
        style={{
          padding: "1rem",
          backgroundColor: "rgba(0,0,0,.815)",
          color: "white",
          borderRadius: "4px",
          width: "100%",
          height: "100%",
        }}
      >
        {logs.length === 0 &&
          [...Array(20).keys()].map((_v, i) => <RconLogSkeleton key={i} />)}
        {logs.length > 0 &&
          logs.map((v, k) => (
            <Box key={k}>
              <Typography variant="subtitle2">{v}</Typography>
            </Box>
          ))}
      </Box>
      <Box
        className="rconActions"
        sx={{ marginTop: "auto", paddingTop: "1rem", width: "100%" }}
      >
        <TextField
          id="outlined-basic"
          label="Command"
          variant="outlined"
          value={cmd}
          onChange={updateCmd}
          disabled={!(rcon && rcon.rconLive && !rcon.rconError)}
          sx={{ width: "100%" }}
        />
        {rcon && rcon.rconLive && !rcon.rconError && (
          <Button onClick={sendCommand} sx={{ padding: "0 2rem" }}>
            Send
          </Button>
        )}
        {!(rcon && rcon.rconLive && !rcon.rconError) && (
          <Button color="secondary">Not Connected</Button>
        )}
      </Box>
    </Box>
  );
}
