import { Link, useNavigate } from "react-router";
import TextField from "../../md-components/TextField";
import FilledButton from "../../md-components/FilledButton";
import { useRef, useState } from "react";
import axios from "axios";
import { toast } from "react-toastify";

function OOBECreateUser() {
  const submitRef = useRef();
  const [processing, setProcessing] = useState(false);
  function handleSubmit(e) {
    if (e.key === "Enter") {
      submitRef.current.click();
    }
  }
  const navigate = useNavigate();
  function createUser(name, username, password) {
    axios
      .post("/oobe/create-user", {
        name: name,
        username: username,
        password: password,
      })
      .then(() => {
        toast(`happy reading ${name}!`);
        axios
          .post("/auth", { login: username, password: password })
          .then(() => {
            axios.get("/user").then((res) => {
              localStorage.setItem("userInfo", JSON.stringify(res.data));
            });
            navigate("/");
          })
          .catch(() => {
            toast.error("Что то пошло не так...");
            setProcessing(false);
          });
      })
      .catch((error) => {
        if (error.response.status === 403) {
          toast.error("OOBE уже завершен, невозможно создать пользователя");
        } else {
          toast.error("Ошибка при создании пользователя");
        }
        setProcessing(false);
      });
  }
  return (
    <>
      <h1 className="font-bold text-2xl mb-6">Создать пользователя</h1>
      <div className="mb-0">
        <span>Введите данные для администратора библиотеки</span>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            if (processing) return;
            setProcessing(true);
            createUser(
              e.target.name.value,
              e.target.username.value,
              e.target.password.value
            );
          }}
          className="flex flex-col gap-3 py-4 items-center"
        >
          <TextField label="Имя" id="name" onKeyDown={handleSubmit} required />
          <TextField
            label="Логин"
            type="username"
            id="username"
            onKeyDown={handleSubmit}
            required
          />
          <TextField
            label="Пароль"
            type="password"
            id="password"
            onKeyDown={handleSubmit}
            required
          />
          <FilledButton
            className="w-50"
            type="submit"
            ref={submitRef}
            disabled={processing}
          >
            {processing ? "Создание..." : "Создать"}
          </FilledButton>
        </form>
      </div>
      <span className="text-center mt-4">v2.0-beta</span>
    </>
  );
}

export default OOBECreateUser;
