import { useFormik } from "formik";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useLoginMutation } from "../../../generated/graphql";

import Button from "../../atoms/Button";
import TextField from "../../molecules/TextField";

const LoginPage = () => {
  const navigator = useNavigate();
  const loginMutation = useLoginMutation();
  const [submitError, setSubmitError] = useState("");

  const loginForm = useFormik({
    initialValues: {
      name: "",
      password: "",
    },
    onSubmit: ({ name, password }) => {
      loginMutation.mutate({ credentials: { name, password } });
    },
  });

  useEffect(() => {
    if (!loginMutation.data) {
      return;
    } else if (loginMutation.data.login.__typename == "CommonError") {
      setSubmitError(loginMutation.data.login.message);
    } else if (loginMutation.data.login.__typename == "AuthSuccess") {
      localStorage.setItem("token", loginMutation.data.login.token);
      navigator("/services");
    }
  }, [loginMutation.data]);

  return (
    <main>
      <div className="flex flex-col justify-center min-h-screen py-12 sm:px-6 lg:px-8">
        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="flex flex-row justify-start items-center w-full space-x-2">
            <div className="w-16 h-16 bg-sky-300 rounded-md" />
            <div>
              <h1 className="text-xl">Traefik</h1>
              <h2 className="block text-2xl font-extrabold tracking-tighter text-gray-900 transition duration-500 ease-in-out transform hover:text-gray-900">
                Confman
              </h2>
            </div>
          </div>
          <div className="py-10">
            <form
              className="space-y-6"
              data-bitwarden-watching="1"
              onSubmit={loginForm.handleSubmit}
            >
              <TextField
                label="Username"
                placeholder="name"
                id="name"
                size="lg"
                onChange={loginForm.handleChange}
                value={loginForm.values.name}
              />
              <TextField
                type="password"
                id="password"
                label="Password"
                size="lg"
                placeholder="*****"
                onChange={loginForm.handleChange}
                value={loginForm.values.password}
              />

              <div>
                <Button type="submit" size="lg">
                  Login
                </Button>
                {submitError && <span>{submitError}</span>}
              </div>
            </form>
          </div>
        </div>
      </div>
    </main>
  );
};

export default LoginPage;
