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";
import { SpinnerIcon } from "../icons";

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("로그인");
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col items-center my-10">
      <div className="w-1/2 md:w-1/3 my-8 text-center text-2xl font-semibold">
        <Link to="/">로그인</Link>
      </div>
      <div className="flex flex-col w-full md:w-3/5 p-8 md:p-4">
        <form
          onSubmit={handleSubmit}
          className="flex flex-col bg-white md:flex-row md:justify-around border-2 border-black rounded-xl p-8 gap-y-4"
        >
          <div className="flex flex-col md:w-2/3 gap-2">
            <input
              className="placeholder:text-slate-300
                bg-white border border-slate-500 rounded-2xl
                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 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 bg-sky-500 hover:bg-sky-400 rounded-xl text-xl py-4 md:px-4 text-white"
          >
            {" "}
            {loading && (
              <SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
            )}
            로그인
          </button>
        </form>
        <div className="flex flex-col">
          {error && (
            <div className="mt-2 text-center text-red-500 text-sm">
              <p>{error}</p>
            </div>
          )}
          <div className="flex justify-around m-4">
            <button>
              <Link to="/signup">회원가입</Link>
            </button>
          </div>
        </div>
      </div>
      <div className="bg-lime-100 h-36" />
    </div>
  );
}
