import './SignUp.css'
import { useForm } from 'react-hook-form'
import { zodResolver } from "@hookform/resolvers/zod"
import { useLocation, Navigate, useNavigate } from 'react-router-dom';
import { Form1Data, Form2Data, form2Schema } from './signUpSchema'

export const SignUpForm2 = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<Form2Data>({
    resolver: zodResolver(form2Schema),
  });
  const location = useLocation();
  const form1 = location.state as Form1Data | null;
  const navigate = useNavigate();

  // form1 のデータがない場合は form1 にリダイレクトする
  if (form1 === null) {
    return <Navigate replace to="/sign-up/form1" />
  }

  const onsubmit = (form2: Form2Data) => {
    const state = { form1, form2 }
    navigate('/sign-up/form3', { state })
  }

  const onerror = (err: any) => console.log(err);

  return (
    <>
      <h1>会員登録 フェーズ 2</h1>
      <form className="SignUpForm" onSubmit={handleSubmit(onsubmit, onerror)}>
        <div>
          <label htmlFor="email">メールアドレス: </label>
          <input id="email" type="email" {...register('email')}></input>
          <div className="error">{errors.email?.message}</div>
        </div>
        <div>
          <label htmlFor="password">パスワード: </label>
          <input id="password" type="password" {...register('password')}></input>
          <div className="error">{errors.password?.message}</div>
        </div>
        <div>
          <button type="submit">次へ</button>
        </div>
      </form>
    </>
  );
}
