import { useState } from 'react';
import { Redirect, Link } from "react-router-dom";
import { Formik } from 'formik';
import * as Yup from 'yup';
import authApi from '../../apis/auth.api';
import catchErrors from "../../utils/catchErrors.js";

const LoginForm = () => {
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  if (success) {
    return <Redirect to="/home" />;
  }
  return (
    <>
      <Formik
        initialValues={{
          userId: '',
          password: '',
        }}
        validationSchema={Yup.object({
          userId: Yup.string()
            .required('아이디를 입력해주세요.'),
          password: Yup.string()
            .required('비밀번호를 입력해주세요.'),
        })}
        onSubmit={async (values, { setSubmitting }) => {
          try {
            setError("")
            const result = await authApi.login(values)
            if (result.status === 201) {
              setSuccess(true)
            }
          } catch (error) {
            catchErrors(error, setError)
          }
          setTimeout(() => {
            setSubmitting(false);
          }, 400);
        }}
      >
        {formik => (
          <form onSubmit={formik.handleSubmit} className="m-5">
            <div className="mb-3">
              <input type="text" name="userId"
                className="form-control border-top-0 border-end-0 border-start-0"
                style={{ boxShadow: "none", borderRadius: "0" }}
                placeholder="아이디"
                {...formik.getFieldProps('userId')} />
              {formik.touched.userId && formik.errors.userId ? (
                <div className="text-danger mt-1" style={{ fontSize: "10px" }}>{formik.errors.userId}</div>
              ) : null}
            </div>
            <div className="mb-3">
              <input type="password" name="password"
                className="form-control border-top-0 border-end-0 border-start-0"
                style={{ boxShadow: "none", borderRadius: "0" }}
                placeholder="비밀번호"
                {...formik.getFieldProps('password')} />
              {formik.touched.password && formik.errors.password ? (
                <div className="text-danger mt-1" style={{ fontSize: "10px" }}>{formik.errors.password}</div>
              ) : null}
            </div>
            <div className="d-grid gap-2 mt-5">
              <button type="submit" className="btn btn-crimson">로그인</button>
              <Link className="btn btn-crimson" to="/signup">회원가입</Link>
            </div>
          </form>
        )}
      </Formik>
    </>
  );
}

export default LoginForm;

