import { LoadingButton } from "@mui/lab";
import { Box, FormControlLabel, Grid, Grid2, Switch, TextField, Typography } from "@mui/material";
import { fetch } from "@tauri-apps/plugin-http";
import { useAtom } from "jotai";
import { useState } from "react";
import { useNotification } from "../../../contexts/NotificationContext";
import { serverUrlAtom } from "../../../lib/jotai";
import { HeaderLogo } from "../../Generic/HeaderLogo";
import { SetupLogItem } from "./SetupLogItem";

export const SqlInjectionSetup = () => {
  // contexts
  const { openNotification } = useNotification();

  // atoms
  const [serverUrl, setServerUrl] = useAtom(serverUrlAtom);

  // states
  const [logs, setLogs] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const setupClickEvent = async () => {
    setLoading(true);

    try {
      const response = await fetch(serverUrl + "/nuke-db", {
        method: "POST",
      });
      const responseText = await response.text();
      if (!response.ok) {
        openNotification("Nuke failed: " + responseText);
      } else {
        openNotification("Nuke successful");
      }

      setLogs((prevLogs) => [...prevLogs.slice(-5), responseText]);

      const response2 = await fetch(serverUrl + "/setup-demo-db", {
        method: "POST",
      });
      const responseText2 = await response2.text();
      if (!response.ok) {
        openNotification("Setup demo DB failed: " + responseText2);
      } else {
        openNotification("Demo database setup successful");
      }

      setLogs((prevLogs) => [...prevLogs.slice(-5), responseText2]);
    } catch (e) {
      // log the error and handle failure
      console.log("Request failed", e);
    } finally {
      // stop loading indicator regardless of success/failure
      setLoading(false);
    }
  };

  return (
    <>
      <Box
        alignItems="center"
        display="flex"
        flexDirection="row"
        sx={{
          mb: 2,
        }}
      >
        <HeaderLogo />
        <Typography
          sx={{
            color: "grey",
          }}
          variant="h6"
        >
          &nbsp;Setup
        </Typography>
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          maxHeight: "100%",
        }}
      >
        <Typography variant="body2">
          Click on the &apos;Setup/reset DB&apos; button below to initialize or reset your database.
        </Typography>
        <Typography variant="body2">
          If you get an error, make sure you have set the correct server URL (check the chip at the top right).
        </Typography>
        <Typography variant="body2">
          Demo email:{" "}
          <b>
            <code style={{ fontFamily: "JetBrainsMono" }}>asdf@gmail.com</code>
          </b>
        </Typography>
        <Typography variant="body2">
          Demo password:{" "}
          <b>
            <code style={{ fontFamily: "JetBrainsMono" }}>asdf</code>
          </b>
        </Typography>
        <LoadingButton
          loading={loading}
          onClick={setupClickEvent}
          size="small"
          sx={{
            my: 2,
          }}
          variant="contained"
        >
          Setup/reset DB
        </LoadingButton>
        {logs.map((log, index) => (
          <SetupLogItem key={index}>{log}</SetupLogItem>
        ))}
      </Box>
    </>
  );
};
