import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { registrationStart, registrationComplete, AUTH_QUERY_KEY } from '@features/auth'
import { tokenStore } from '@shared/api/tokenStore'
import { clearCsrfCache } from '@shared/api/csrf'
import { ROUTES } from '@shared/config/routes'
import type { ApiErrorResponse } from '@shared/api/types'

function extractErrorMessage(error: unknown): string {
  const apiError = error as ApiErrorResponse
  return apiError?.detail?.[0]?.msg ?? 'Произошла ошибка'
}

export function useRegisterForm() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [codeSent, setCodeSent] = useState(false)
  const [passwordError, setPasswordError] = useState<string | null>(null)

  const startMutation = useMutation({
    mutationFn: registrationStart,
    onSuccess: () => setCodeSent(true),
  })

  const completeMutation = useMutation({
    mutationFn: registrationComplete,
    onSuccess: async ({ access_token }) => {
      clearCsrfCache()
      queryClient.clear()
      if (access_token) tokenStore.set(access_token)
      await queryClient.invalidateQueries({ queryKey: AUTH_QUERY_KEY })
      navigate(ROUTES.WALLET)
    },
  })

  const handleRequestCode = () => {
    if (!email) return
    startMutation.mutate({ email })
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (password !== confirmPassword) {
      setPasswordError('Пароли не совпадают')
      return
    }
    setPasswordError(null)
    completeMutation.mutate({ email, password, confirm_password: confirmPassword, code: verificationCode })
  }

  const error =
    passwordError ??
    (startMutation.isError ? extractErrorMessage(startMutation.error) : null) ??
    (completeMutation.isError ? extractErrorMessage(completeMutation.error) : null)

  return {
    email, setEmail,
    password, setPassword,
    confirmPassword, setConfirmPassword,
    verificationCode, setVerificationCode,
    codeSent,
    isLoadingCode: startMutation.isPending,
    isLoadingSubmit: completeMutation.isPending,
    error,
    handleRequestCode,
    handleSubmit,
  }
}
