import { useController } from 'react-hook-form'
import { useModalStore } from '@/store'
import { useLoginForm } from '../hooks/use-login-form'
import { DesktopLoginFormView } from './desktop-login-form-view'

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

export function DesktopLoginForm({ onSuccess }: DesktopLoginFormProps) {
  const { form, isSubmitting, onSubmit, submitError } = useLoginForm({
    onSuccess,
  })
  const setModalOpen = useModalStore((state) => state.setModalOpen)
  const usernameField = useController({
    control: form.control,
    name: 'username',
  })
  const passwordField = useController({
    control: form.control,
    name: 'password',
  })

  function handleSwitchToRegister() {
    setModalOpen('desktopLogin', false)
    setModalOpen('desktopRegister', true)
  }

  return (
    <DesktopLoginFormView
      username={usernameField.field.value ?? ''}
      password={passwordField.field.value ?? ''}
      errors={{
        password: form.formState.errors.password?.message,
        username: form.formState.errors.username?.message,
      }}
      isSubmitting={isSubmitting}
      onPasswordChange={passwordField.field.onChange}
      onSubmit={onSubmit}
      onSwitchToRegister={handleSwitchToRegister}
      onUsernameChange={usernameField.field.onChange}
      submitError={submitError}
    />
  )
}
