import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { loginStart, loginComplete, 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 useLoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [codeSent, setCodeSent] = useState(false)
  const queryClient = useQueryClient()
  const navigate = useNavigate()

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

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

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    completeMutation.mutate({ email, password, code: verificationCode })
  }

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

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