import { Box, Button, Chip, CircularProgress, Popover, Stack } from "@mui/material";
import { fetch } from "@tauri-apps/plugin-http";
import { useAtom } from "jotai";
import { MouseEvent, useEffect, useState } from "react";
import { serverConnectionAtom, serverUrlAtom } from "../../lib/jotai";
import { defaultSettings } from "../../lib/settings";
import { ServerUrlInput } from "./ServerUrlInput";
import { sleep } from "../../lib/utility";

export const ServerStatus = () => {
  // atoms
  const [serverConnection, setServerConnection] = useAtom(serverConnectionAtom);
  const [serverUrl, setServerUrl] = useAtom(serverUrlAtom);

  // use states
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);

  const clickEvent = (event: MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const dialogCloseEvent = () => {
    setAnchorEl(null);
  };

  // function to check server health
  const checkServerConnection = async () => {
    setServerConnection("connecting");

    // remove trailing slash
    setServerUrl(serverUrl.replace(/\/$/, ""));

    try {
      const response = await fetch(serverUrl + "/health");
      if (response.ok) {
        console.log("connected");
        setServerConnection("connected");
      } else {
        console.log("disconnected");
        await sleep(500);
        setServerConnection("disconnected");
      }
    } catch (e) {
      console.log("disconnected", e);
      await sleep(500);
      setServerConnection("disconnected");
    }
  };

  const chipProps = {
    color: serverConnection === "connected" ? "success" : serverConnection === "disconnected" ? "error" : "warning",
    label:
      serverConnection === "connected"
        ? "Server connected"
        : serverConnection === "disconnected"
        ? "Server disconnected"
        : "Connecting...",
  };

  useEffect(() => {
    // only start interval if server is connected
    if (serverConnection === "connected") {
      const intervalId = setInterval(checkServerConnection, 2000);
      console.log("Started server ping interval");

      // cleanup interval on disconnection or component unmount
      return () => {
        clearInterval(intervalId);
        console.log("Stopped server ping interval");
      };
    }
  }, [serverConnection, serverUrl]);

  return (
    <Box
      sx={{
        alignItems: "center",
        display: "flex",
        flexDirection: "row",
        p: 1,
      }}
    >
      {serverConnection === "connecting" && (
        <CircularProgress
          size='20px'
          sx={{ mr: 1 }}
        />
      )}
      {/* @ts-ignore */}
      <Chip
        {...chipProps}
        onClick={clickEvent}
        size='small'
      />
      <Popover
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
        onClose={dialogCloseEvent}
        open={Boolean(anchorEl)}
        transformOrigin={{
          vertical: "top",
          horizontal: "center",
        }}
        sx={{
          "transform": "translate(0px, 8px)",
          "& .MuiPaper-root": {
            borderRadius: defaultSettings.style.radius + "px",
          },
        }}
      >
        <Box
          sx={{
            backgroundColor: "#434446",
            p: 2,
          }}
        >
          <form
            onSubmit={(e) => {
              checkServerConnection();
              e.preventDefault();
            }}
          >
            <Stack
              alignItems='center'
              display='flex'
              direction='row'
              spacing={1}
            >
              <ServerUrlInput />
              <Button
                type='submit'
                variant='outlined'
              >
                Connect
              </Button>
            </Stack>
          </form>
        </Box>
      </Popover>
    </Box>
  );
};
