import Input from "../components/UI/Input.tsx";
import Button from "../components/UI/Button.tsx";
import React, {useState} from "react";
import api from "../api.tsx";
import {useAuth} from "../context/AuthContext.tsx";
import {useNavigate} from "react-router-dom";


export function LoginPage() {
  const [login,setLogin] = useState('');
  const [password, setPassword] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [registerResultMessage, setRegisterResultMessage] = useState('');
  const auth = useAuth();
  const navigate = useNavigate();

  function loginFormSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    api.post('user/login', {
      username: login,
      password: password,
    }).then((response) => {
      auth.login(response.data.token);
      setErrorMessage('');
      navigate('/');
    }).catch((err) => {
      console.log(err);
      if(err.status === 401) {
        setErrorMessage('Wrong username or password');
      } else {
        setErrorMessage('Something went wrong');
      }
    })
  }

  function registerBtnClick() {
    api.post('user/register', {
      username: login,
      password: password,
    }).then((response) => {
      if(response.status === 201) {
        setRegisterResultMessage('User registered successfully. You can now log in.');
        setErrorMessage('');
      }
    }).catch(() => {
      setErrorMessage('Something went wrong');
    });
  }

  return <>
    <div className={"flex flex-col items-center mb-4 pt-4"}>
      <div className={"lg:w-80 sm:w-3/4"}>
        <h1 className={"text-3xl text-center"}>Login</h1>
        <p className={"text-gray-400"}>
          Before use this app you need to have account
        </p>
      </div>
    </div>
    <div className={"flex flex-col items-center"}>
      <div className={"lg:w-80 sm:w-3/4"}>
        { errorMessage && (
            <div className={"p-4 rounded bg-red-200 text-black"}>
              { errorMessage }
            </div>
        )}
        { registerResultMessage && (
            <div className={"p-4 rounded bg-blue-800 text-white"}>
              {registerResultMessage}
            </div>
        )}
        <form onSubmit={loginFormSubmit}>
          <Input type="text"
                 label="Login"
                 placeholder="Enter your login"
                 value={login}
                 name={"login"}
                 onChange={(e) => setLogin(e.target.value) }
                 error={false} />

          <Input type={"password"}
                 label={"Password"}
                 value={password}
                 placeholder={"Enter your password"}
                 error={false}
                 name={"password"}
                 onChange={(e)=>setPassword(e.target.value) } />
          <Button type={"submit"} className={"w-full mt-8"}
                  disabled={login.length < 3 || password.length < 3}>
            Login
          </Button>
          <p className={"text-center"}>- or -</p>
          <Button  className={"w-full bg-gray-500"}
                   disabled={login.length < 3 || password.length < 3}
                   onClick={() => registerBtnClick()}>
            Create account
          </Button>
        </form>

      </div>
    </div>

  </>
}