import { useRef, useState, FormEvent } from 'react'
import SingleColumnLayout from '../../../layouts/SingleColumnLayout.tsx'
import TextInput from '../../../components/TextInput.tsx'
import PrimaryButton from '../../../components/PrimaryButton.tsx'
import { AuthService } from '../authService.ts'
import { useNavigate } from 'react-router-dom'
import SecondaryNavButton from '../../../components/SecondaryNavButton.tsx'

interface LoginPageProps {
  authService: AuthService
}

export default function LoginPage({ authService }: LoginPageProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const usernameInputRef = useRef<HTMLInputElement | null>(null)
  const passwordInputRef = useRef<HTMLInputElement | null>(null)
  const navigate = useNavigate()

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()

    if (!username) {
      setError("you didn't username D:<")
      return
    }

    if (!password) {
      setError("you didn't password D:<")
      return
    }

    setError(null)

    setIsSubmitting(true)

    try {
      await authService.login(username, password)
      navigate('/')
    } catch (error: unknown) {
      setError(error instanceof Error ? error.message : 'something went terribly wrong')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <SingleColumnLayout>
      <main className="w-full mx-auto p-4">
        <div className="mt-12">
          <form className="flex flex-col gap-4 max-w-md" onSubmit={onSubmit}>
            <div className="flex flex-col gap-1">
              <label htmlFor="username" className="text-sm text-gray-600">
                username
              </label>
              <TextInput
                ref={usernameInputRef}
                id="username"
                value={username}
                onInput={setUsername}
              />
            </div>

            <div className="flex flex-col gap-1">
              <label htmlFor="password" className="text-sm text-gray-600">
                password
              </label>
              <TextInput
                ref={passwordInputRef}
                type="password"
                id="password"
                value={password}
                onInput={setPassword}
              />
            </div>

            <PrimaryButton className="mt-4" disabled={isSubmitting} type="submit">
              {isSubmitting ? 'wait...' : 'make login pls'}
            </PrimaryButton>

            <SecondaryNavButton to={'/signup'}>register instead?</SecondaryNavButton>

            <span className="text-xs h-3 text-red-500">{error}</span>
          </form>
        </div>
      </main>
    </SingleColumnLayout>
  )
}
