import React, { useState, useEffect } from "react";
import { NextPage } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import styled from "styled-components";
import { generateToken, setTokenCookie, isAuthenticated } from "@utils/auth";
import AdminPageWrapper from "@views/common/AdminPageWrapper";

const Main = styled.div`
  input {
    display: block;
  }
`;

const DEFAULT_REDIRECT = "/admin";
const AdminLoginPage: NextPage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const router = useRouter();
  const next = router.query.next as string || DEFAULT_REDIRECT;

  useEffect(() => {
    isAuthenticated().then((res) => {
      if (res) {
        router.push(next);
      }
    });
  }, [router, next]);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      const token = await generateToken(username, password);
      setTokenCookie(token);
      router.push(next);
    } catch (err) {
      setError("Failed to log in!");
    }
  };

  return (
    <>
      <Head>
        <link rel="canonical" href="https://sik.ayy.fi/admin/login" />
      </Head>
      <AdminPageWrapper requiresAuthentication={false}>
        <Main>
          <h1>Log in to SIK Admin</h1>
          {next && next !== DEFAULT_REDIRECT && (
            <div className="error">You have to log in first.</div>
          )}
          <form className="admin-login-form" onSubmit={handleSubmit}>
            <label>Username
              <input
                id="login-username"
                type="text"
                name="username"
                value={username}
                onChange={(e) => {
                  setUsername(e.target.value);
                }}
              />
            </label>
            <label>Password
              <input
                id="login-password"
                type="password"
                name="password"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                }}
              />
            </label>
            <input id="login-submit" type="submit" value="Log in" />
          </form>
          {error && (
            <div className="error">
              {error}
            </div>
          )}
        </Main>
      </AdminPageWrapper>
    </>
  );
};

export default AdminLoginPage;
