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

import { useQuery, QueryClient, QueryClientProvider } from 'react-query'

export const SignUpForm3 = () => {
  const queryClient = new QueryClient()

  return (
    <QueryClientProvider client={queryClient}>
      <SignUpForm3Main />
    </QueryClientProvider>
  )
}


export const SignUpForm3Main = () => {
  const { register, watch, setValue, handleSubmit, formState: { errors } } = useForm<Form3Data>({
    resolver: zodResolver(form3Schema),

  });
  const location = useLocation();
  const formData = location.state as { form1: Form1Data, form2: Form2Data } | null;
  const navigate = useNavigate();
  const watchHasGitHubRepo = watch("hasGitHubRepo", false)
  const gitHubUsername = watch("gitHubUsername", '')

  const repoQueryEnabled = watchHasGitHubRepo && gitHubUsername.length > 0;

  console.log(gitHubUsername)
  console.log(repoQueryEnabled)

  const { data: reposData, isLoading: reposIsLoading, isError: reposIsError, error: reposError } = useQuery({
    queryKey: ['gitHubRepos', gitHubUsername],
    queryFn: async () => {
      const res = await fetch(`https://api.github.com/users/${gitHubUsername}/repos?sort=updated&direction=desc&per_page=100`)
      if (res.ok) { return res.json(); }
      throw new Error(res.statusText)
    },
    enabled: repoQueryEnabled,
  })

  const repoNames: [string] = (repoQueryEnabled && !reposIsLoading && !reposIsError) ?
    (reposData.map((json: any) => (json['name']))) :
    []

  useEffect(() => {
    setValue('gitHubUsername', '')
    setValue('repoName', '')
  }, [watchHasGitHubRepo])

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

  const { form1, form2 } = formData;

  const onsubmit = (form3: Form3Data) => {
    const state = { form1, form2, form3 }
    navigate('/sign-up/confirm', { state })
  }
  const onerror = (err: any) => console.log(err);

  return (
    <>
      <h1>会員登録 フェーズ 3</h1>
      <form className="SignUpForm" onSubmit={handleSubmit(onsubmit, onerror)}>
        <div>
          <label htmlFor="hasGitHubRepo">GitHubのリポジトリある？: </label>
          <input id="hasGitHubRepo" type="checkbox" {...register('hasGitHubRepo')}></input>
          <div className="error">{errors.hasGitHubRepo?.message}</div>
        </div>
        {
          (watchHasGitHubRepo &&
            <div>
              <label htmlFor="gitHubUsername">github username: </label>
              <input id="gitHubUsername" type="text" {...register('gitHubUsername')}></input>
            </div>
          )
        }
        {
          repoQueryEnabled && (
            (
              reposIsLoading ? 'Loading...' :
                reposIsError ? `Error: ${reposError}` :
                  <div>
                    <label htmlFor="repoName">お気に入りのリポジトリを選んでください:</label>
                    <select id="repoName" {...register('repoName')}>
                      {repoNames.map((repoName) => (
                        <option key={repoName} value={repoName}>{repoName}</option>
                      ))}
                    </select>
                  </div>
            )
          )
        }
        <div>
          <button type="submit">確認画面へ</button>
        </div>
      </form >
    </>
  );
}
