import { LoadingButton } from "@mui/lab";
import { Box, FormControlLabel, 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";

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

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

  // states
  const [emailValueRaw, setEmailValueRaw] = useState<string>("");
  const [passwordValueRaw, setPasswordValueRaw] = useState<string>("");
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [loginLoading, setLoginLoading] = useState<boolean>(false);
  const [secured, setSecured] = useState<boolean>(false);

  const nextClickEvent = async () => {
    // reset the error messages
    setErrorMsg("");

    // ensure that the server url does not end with a trailing slash
    setServerUrl(serverUrl.replace(/\/$/, ""));

    // construct the request body
    const requestBody = {
      email: emailValueRaw,
      password: passwordValueRaw,
    };

    // start loading indicator
    setLoginLoading(true);

    const endpointUrl = serverUrl + (secured ? "/secure-login-sql" : "/unsecure-login-sql");

    try {
      // make request good
      const response = await fetch(endpointUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestBody),
      });

      // check if login was successful
      if (!response.ok) {
        const errorMessage = await response.text();
        console.log("Login failed:", errorMessage);
        setErrorMsg(errorMessage);
      } else {
        openNotification("Login successful");
      }
    } catch (e) {
      // log the error and handle failure
      console.log("Request failed", e);
    } finally {
      // stop loading indicator regardless of success/failure
      setLoginLoading(false);
    }
  };

  return (
    <>
      <Box
        alignItems="center"
        display="flex"
        flexDirection="row"
        sx={{
          mb: 2,
        }}
      >
        <HeaderLogo />
        <Typography
          sx={{
            color: "grey",
          }}
          variant="h6"
        >
          &nbsp;Login
        </Typography>
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
        }}
      >
        <form
          onSubmit={(e) => {
            e.preventDefault();
            nextClickEvent();
          }}
        >
          <TextField
            fullWidth
            id="email"
            label="Email"
            onChange={(e: { target: { value: string } }) => setEmailValueRaw(e.target.value)}
            size="small"
            type="text"
            value={emailValueRaw}
            sx={{ mb: 2 }}
            variant="outlined"
          />
          <TextField
            error={Boolean(errorMsg)}
            fullWidth
            helperText={Boolean(errorMsg) ? errorMsg : ""}
            id="password"
            label="Password"
            onChange={(e: { target: { value: string } }) => setPasswordValueRaw(e.target.value)}
            size="small"
            type="password"
            value={passwordValueRaw}
            sx={{ mb: 2 }}
            variant="outlined"
          />
          <Box
            sx={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-between",
            }}
          >
            <FormControlLabel
              control={
                <Switch
                  checked={secured}
                  onChange={(e) => {
                    setSecured(e.target.checked);
                  }}
                />
              }
              label="Use secure endpoint"
            />
            <LoadingButton
              loading={loginLoading}
              type="submit"
              variant="contained"
            >
              Next
            </LoadingButton>
          </Box>
        </form>
      </Box>
    </>
  );
};
