import React, { useState } from "react";
import{ Link } from "react-router-dom";

function Login() {
  const [userPass, setUserPass] = useState('');
  const [userName, setUserName] = useState('');
  const [message, setMessage] = useState('');

  function handleUserName(e){
    setUserName(e.target.value);
  }
  function handleUserPass(e){
    setUserPass(e.target.value);
  }
  const handleSubmit = async (e) => {


    try{
      const response = await fetch('http://localhost:8000/login-m.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'credentials': 'include'
        },
        body: JSON.stringify({
          user: userName,
          password: userPass
        })
      });
      const data = await response.json();
      if(data.state === 'loggedin'){
        window.location.href = "/center";
      }
      else {
        setMessage(data.message);

      }
    }catch(err){
      console.log(err);
    }

  }
    return  <>
    <h2>
      <i className="fa-solid fa-pen-to-square" /> Login
    </h2>
    <form method="post" onSubmit={handleSubmit} >
      <input
        type="text"
        name="user"
        placeholder="Username / Mail"
        minLength={3}
        maxLength={16}
        value={userName}
        onChange={handleUserName}
      />
      <br />
      <input type="password" name="password" placeholder="Password" value={userPass} onChange={handleUserPass}/>
      <br />
      <input type="submit" placeholder="Submit" />
    </form>
    <p>{message}</p>
    <p>New to crumbs? | <Link to="/register">Register</Link></p>
  </>;
  
};

export default Login;