import React, { FormEvent, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { authApi } from "../apis";
import { catchErrors } from "../helpers";
import { SpinnerIcon } from "../icons";
import { SignupUser } from "../types";

export default function Signup() {
  const [user, setUser] = useState<SignupUser & { password2: string }>({
    name: "",
    email: "",
    password: "",
    password2: "",
  });

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

  useEffect(() => {
    setDisabled(!(user.name && user.email && user.password && user.password2));
  }, [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("checkPassword:", passwordMatch());
      console.log("user data", user);
      if (passwordMatch()) {
        const { password2, ...sUser } = user;
        setLoading(true);
        const res = await authApi.signup(sUser);
        console.log("서버연결됬나요", res);
        console.log("회원가입");
        setSuccess(true);
        setError("");
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

  function passwordMatch() {
    if (user.password !== user.password2) {
      // alert();
      setError("비밀번호가 일치하지않습니다");
      console.log("password fail");
      return false;
    } else {
      console.log("password match");
      return true;
    }
  }

  if (success) {
    alert("회원가입 되었습니다");
    navigate("/login", { replace: true });
  }

  return (
    <div className="flex flex-col items-center">
      <div className="p-12 md:w-40 mt-8 bg-red-400 rounded-2xl">
        <Link to="/">Travel Report</Link>
      </div>
      <form
        onSubmit={handleSubmit}
        className="flex flex-col items-center mt-16 gap-y-4"
      >
        <input
          className="placeholder:text-slate-300 bg-white border border-slate-500 rounded-2xl py-2 pl-9 pr-3 focus:border-black"
          placeholder="이름"
          type="text"
          name="name"
          onChange={handleChange}
        />

        <input
          className="placeholder:text-slate-300 bg-white border border-slate-500 rounded-2xl py-2 pl-9 pr-3 focus:border-black"
          placeholder="이메일"
          type="email"
          name="email"
          onChange={handleChange}
        />

        <input
          className="placeholder:text-slate-300
          bg-white border border-slate-500 rounded-2xl
          py-2 pl-9 pr-3
          focus:border-black"
          placeholder="비밀번호"
          type="password"
          name="password"
          onChange={handleChange}
        />

        <input
          className="placeholder:text-slate-300
          bg-white border border-slate-500 rounded-2xl
          py-2 pl-9 pr-3
          focus:border-black"
          placeholder="비밀번호 확인"
          type="password"
          name="password2"
          onChange={handleChange}
        />
        {error && (
          <div className="text-red-500 text-sm">
            <p>{error}</p>
          </div>
        )}
        <button disabled={disabled} className="border-b border-white">
          {loading && (
            <SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
          )}
          회원가입
        </button>
      </form>
    </div>
  );
}
