import { Link, useNavigate } from "react-router-dom";
import React, { useState, useEffect, FormEvent } from "react";
import { LoginUser } from "../types";
import { catchErrors } from "../helpers";
import { useAuth } from "./auth.context";

export default function Login() {
  const [user, setUser] = useState<LoginUser>({
    email: "",
    password: "",
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [disabled, setDisabled] = useState(false);
  const [success, setSuccess] = useState(false);
  const navigate = useNavigate();
  const { login } = useAuth();

  useEffect(() => {
    setDisabled(!(user.email && user.password));
  }, [user]);

  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    const { name, value } = event.currentTarget;
    setUser({ ...user, [name]: value });
  }

  async function handleSubmit(event: FormEvent) {
    event.preventDefault();
    try {
      setError("");
      console.log("user data", user);

      // setLoading(true);
      await login(user.email, user.password, () => {
        navigate("/", { replace: true });
      });
      // console.log("서버연결됬나요", res);
      // console.log("로그인");
      // setSuccess(true);
      // setError("");
    } catch (error) {
      console.log("에러발생");
      // setError("이메일 혹은 비밀번호를 다시 입력해주세요.");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col items-center my-10">
      <div className="bg-white w-1/2 md:w-1/3 my-8 text-center text-2xl">
        <Link to="/">Travel Report</Link>
      </div>
      <div className="flex flex-col w-full md:w-1/3 p-8 md:p-4 md:p-0">
        <form onSubmit={handleSubmit}>
          <div className="flex flex-col md:flex-row border-2 border-black rounded-xl p-8 md:p-12 gap-y-4 md:gap-x-6">
            <div className="flex flex-col md:w-2/3 md:gap-2 ">
              <input
                className="placeholder:text-slate-300
                bg-white border border-slate-500 md:rounded-2xl
                my-2 py-3 md:py-2 pl-9 pr-3 
                focus:border-black
                "
                placeholder="이메일"
                type="email"
                name="email"
                onChange={handleChange}
              />

              <input
                className="placeholder:italic placeholder:text-slate-300
                bg-white border border-slate-500 md:rounded-2xl
                py-3 md:py-2 pl-9 pr-3 
                focus:border-black
                "
                placeholder="Password"
                type="password"
                name="password"
                onChange={handleChange}
              />
            </div>
            <button
              disabled={disabled}
              type="submit"
              className="my-4 md:my-0 md:w-1/3 bg-sky-600 hover:bg-sky-700 rounded-xl text-xl py-4"
            >
              login
            </button>
          </div>
        </form>
        <div className="flex justify-around m-4">
          <button className="bg-white ">
            <Link to="/signup">회원가입</Link>
          </button>
          <div className="grid grid-cols-2 divide-x-2">
            <div></div>
            <div></div>
          </div>
          <button className="bg-white">
            <Link to="/forgot">비밀번호 찾기</Link>
          </button>
        </div>
      </div>
    </div>
  );
}
