import { useState } from "react";
import api from "../utils/api";
import { useNavigate } from "react-router-dom";

const Login = ({ setAuthorized }: { setAuthorized: Function }) => {
  const [mail, setMail] = useState("");
  const [password, setPassword] = useState("");
  const navigate = useNavigate();
  const onClick = async () => {
    const resp = await api.post("/login", { mail, password });
    if (resp.status === 200) {
      localStorage.setItem(
        "token",
        JSON.stringify(resp.data).replace(/"/g, ""),
      );
      setAuthorized(true);
      navigate("/");
    } else {
      alert(resp);
    }
  };
  return (
    <>
      <label>Email:</label>
      <input
        type="text"
        value={mail}
        onChange={(e) => setMail(e.target.value)}
      />
      <br />
      <label>Password:</label>
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <br />
      <button onClick={onClick}>Login</button>
    </>
  );
};

export default Login;
