import { useController } from 'react-hook-form'
import { useRegisterForm } from '../hooks/use-register-form'
import { DesktopRegisterFormView } from './desktop-register-form-view'

interface DesktopRegisterFormProps {
  onSuccess?: () => void
}

export function DesktopRegisterForm({ onSuccess }: DesktopRegisterFormProps) {
  const { form, isSubmitting, onSubmit, submitError } = useRegisterForm({
    onSuccess,
  })
  const usernameField = useController({
    control: form.control,
    name: 'username',
  })
  const passwordField = useController({
    control: form.control,
    name: 'password',
  })
  const confirmPasswordField = useController({
    control: form.control,
    name: 'confirmPassword',
  })
  const inviteCodeField = useController({
    control: form.control,
    name: 'inviteCode',
  })

  return (
    <DesktopRegisterFormView
      username={usernameField.field.value ?? ''}
      password={passwordField.field.value ?? ''}
      confirmPassword={confirmPasswordField.field.value ?? ''}
      inviteCode={inviteCodeField.field.value ?? ''}
      errors={{
        confirmPassword: form.formState.errors.confirmPassword?.message,
        inviteCode: form.formState.errors.inviteCode?.message,
        password: form.formState.errors.password?.message,
        username: form.formState.errors.username?.message,
      }}
      isSubmitting={isSubmitting}
      onConfirmPasswordChange={confirmPasswordField.field.onChange}
      onInviteCodeChange={inviteCodeField.field.onChange}
      onPasswordChange={passwordField.field.onChange}
      onSubmit={onSubmit}
      onUsernameChange={usernameField.field.onChange}
      submitError={submitError}
    />
  )
}
