import React, { useState } from 'react'
import styles from "./LoginPage.module.css";
import { Link, redirect,useNavigate } from 'react-router-dom';

function LoginPage() {
    
    const login_url = process.env.REACT_APP_BACKEND_URL + "/login";
    const [errors, setErrors] = useState({});
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();
        // console.log(e.target);

        setErrors({});
        const res = await fetch(login_url, {
            method: "POST",
            credentials: "include",
            body: new FormData(e.target),
        })

        if (!res.ok) {
            // setErrors(re)
            const data = await res.json();
            if ("error" in data) {
                setErrors(data);
            }
            if ("field_error" in data) {
                setErrors(data.field_error);
            }
        }
        else {
            // handle redirect to home page
            console.log("success");
            navigate("/");
            
        }

    }


    return (
        <div id={styles.login_page}>
            <form id={styles.login_form} onSubmit={handleSubmit}>
                <h2>Login</h2>
                {errors.error && (
                    <p className={styles.error_msg}>{errors.error}</p>
                )}
                <div className={styles.input_box}>
                    <label htmlFor="username">Username</label>
                    <input type="text" name="username" id="username" />
                    {errors.username && (
                        <p className={styles.error_msg}>{errors.username[0]}</p>
                    )}
                </div>
                <div className={styles.input_box}>
                    <label htmlFor="username">Password</label>
                    <input type="password" name="password" id="password" />
                    {errors.password && (
                        <p className={styles.error_msg}>{errors.password[0]}</p>
                    )}
                </div>

                <input id={styles.submit_btn} type="submit" value="login" />
            
                <Link to="/signup" id={styles.redirect_link}>Create new account</Link>
            </form>
        </div>
    )
}

export default LoginPage