import React, { useEffect, useState } from 'react';
import Logo from '../components/Logo'
import styles from "./Page.module.css";
import {useAuth} from "../contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import Button from "../components/Button";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  const { login, isAuthenticated, isRegistratonEnabled } = useAuth();
  const navigate = useNavigate();

  async function handleSubmit(e) {
    e.preventDefault();
    if (!username || !password) {
      setErrorMessage("Username and password are required.");
      setShowError(true);
      return;
    }

    try {
      setShowError(false); 
      await login(username, password);
    } catch (err) {
      setErrorMessage("Invalid username or password.");
      setShowError(true);
    }
  }

  useEffect(() => {
    if (isAuthenticated) {
      navigate("/app");
    }
  }, [isAuthenticated, navigate]);
  return (
    <main className={styles.page}>
      <form className={styles.form} onSubmit={handleSubmit}>
        <div className={styles.row}>
          <Logo className={styles.logo} />
        </div>

        {showError && (
          <div className={styles.row}>
            <div className={styles.error}>
              <h1>{errorMessage}</h1>
            </div>
          </div>
        )}

        <div className={styles.row}>
          <label htmlFor="username">Username</label>
          <input
            id="username"
            onChange={(e) => setUsername(e.target.value)}
            value={username}
          />
        </div>

        <div className={styles.row}>
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            onChange={(e) => setPassword(e.target.value)}
            value={password}
          />
        </div>
        
        <div className={styles.btnrow}>
          <Button type="primary">Login</Button>

        {isRegistratonEnabled && (
              <a className={styles.secondbtn} href="/register">Create account</a>
        )}
        </div>
      </form>

    </main>
  );
}
