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

interface FormInput {
  f_name: string;
  l_name: string;
  mail: string;
  password: string;
  password2: string;
}
const Register = () => {
  const [params, setParams] = useState<FormInput>({
    f_name: "",
    l_name: "",
    mail: "",
    password: "",
    password2: "",
  });
  const navigate = useNavigate();
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (params.password !== params.password2) {
      alert("Password dont match");
      return;
    }
    if (params.f_name.length > 30 || params.f_name.length < 2) {
      alert("fname wrong size");
      return;
    }
    if (params.l_name.length > 30 || params.l_name.length < 2) {
      alert("l name wrong size");
      return;
    }
    if (params.mail.length > 50 || params.mail.length < 6) {
      alert("mail wrong size");
      return;
    }
    if (params.password.length > 30 || params.password.length < 10) {
      alert("password wrong size");
      return;
    }
    const resp = await api.post("/register", {
      f_name: params.f_name,
      l_name: params.l_name,
      mail: params.mail,
      password: params.password,
    });
    if (resp.status === 200) {
      navigate("/login");
    } else {
      alert(resp);
    }
  };
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setParams({ ...params, [e.target.name]: e.target.value });
  };
  return (
    <>
      <form onSubmit={onSubmit}>
        <label>First name:</label>
        <input
          type="text"
          name="f_name"
          value={params.f_name}
          onChange={onChange}
        />
        <br />
        <label>Last name:</label>
        <input
          type="text"
          name="l_name"
          value={params.l_name}
          onChange={onChange}
        />
        <br />
        <label>email:</label>
        <input
          type="text"
          name="mail"
          value={params.mail}
          onChange={onChange}
        />
        <br />
        <label>Password:</label>
        <input
          type="password"
          name="password"
          value={params.password}
          onChange={onChange}
        />
        <br />
        <label>Repat Password:</label>
        <input
          type="password"
          name="password2"
          value={params.password2}
          onChange={onChange}
        />
        <br />
        <button type="submit">Register</button>
      </form>
    </>
  );
};

export default Register;
