import { useCallback, useRef, useState } from 'react'
import type { Principal } from '@platform-modules/auth'
import type { SignUpInput } from './client.js'
import { useAuthContext } from './AuthProvider.js'

export function useSignUp() {
  const { client, setUser } = useAuthContext('useSignUp')
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  const clientRef = useRef(client)
  clientRef.current = client

  const signUp = useCallback(async (input: SignUpInput): Promise<Principal> => {
    setPending(true)
    setError(null)
    try {
      const principal = await clientRef.current.signUp(input)
      setUser(principal)
      setPending(false)
      return principal
    } catch (e: unknown) {
      const err = e instanceof Error ? e : new Error(String(e))
      setError(err)
      setPending(false)
      throw err
    }
  }, [setUser])

  return { signUp, pending, error }
}
