'use client'
import { CardWrapper } from '@/components/auth/card-wrapper'
import { AUTH_LOGIN_URL } from '@/config/routes'
import { useI18n } from '@/locales/client'
import { useCallback, useEffect, useState } from 'react'
import { userVerification } from '@/actions/user-verification'
import FormSuccess from '@/components/form-success'
import FormError from '@/components/form-error'
import { Bars } from 'react-loader-spinner'

const UserVerificationForm = ({ token }: { token: string }) => {
  const [error, setError] = useState<string | undefined>(undefined)
  const [success, setSuccess] = useState<string | undefined>(undefined)

  const onSubmit = useCallback(() => {

    userVerification(token).then(data => {
      setSuccess(data?.success)
      setError(data?.error)
    }).catch(() => {
      setError('something went wrong')
    })
  }, [token])

  useEffect(() => onSubmit(), [onSubmit])

  const t = useI18n()

  return (<CardWrapper
    headerTitle={t('auth.title')}
    headerLabel={t('auth.form.verification.header_label')}
    backButtonLabel={t('auth.form.verification.back_button_label')}
    backButtonHref={AUTH_LOGIN_URL}
  >
    <div className="w-full flex items-center justify-center">
      <Bars visible={!success && !error} color="hsl(var(--primary))" ariaLabel="loading" wrapperClass="opacity-50"/>
      <FormSuccess message={success}/>
      <FormError message={error}/>
    </div>
  </CardWrapper>)
}

export default UserVerificationForm
