'use client'

import { useRouter, useSearchParams } from 'next/navigation'
import { getCookie, setCookie } from '@/util/cookie'
import { Suspense, useEffect, useState } from 'react'
import { HomeButton } from '@/app/components/HomeButton'
import { DiscordButton } from '@/app/components/DiscordButton'
import axios from 'axios'

function LoginForm ({ redirect }: { redirect: string | null }) {
  const [loading, setLoading] = useState<boolean>(true)
  const router = useRouter()

  const [username, setUsername] = useState<string>('')
  const [password, setPassword] = useState<string>('')

  useEffect(() => {
    document.title = 'Lncvrt Games - Account Login'

    const token = getCookie('accountToken', '-1')
    if (token !== '-1') {
      router.push('/account')
    } else setLoading(false)
  }, [router])

  return (
    <div className='box'>
      <HomeButton />
      <DiscordButton />
      <p className={`px-8 ${loading ? '-my-2' : 'mb-4 -mt-2'} text-center`}>
        {loading ? 'Loading...' : 'Lncvrt Games Login'}
      </p>
      {!loading && (
        <form
          className='flex flex-col gap-2'
          onSubmit={async e => {
            e.preventDefault()

            try {
              const result = await axios.post('/api/account/login', {
                username,
                password
              })
              if (result.data.success) {
                if (result.data.data.session)
                  setCookie('accountToken', result.data.data.session)
                if (result.data.data.username)
                  setCookie('accountUsername', result.data.data.username)
                if (result.data.data.id)
                  setCookie('accountId', result.data.data.id)

                router.push(redirect ?? '/account')
              } else {
                alert(
                  'Failed to login, error: ' + (result.data.message || 'n/a')
                )
              }
            } catch (e: any) {
              if (e.response) {
                alert(
                  'Failed to login, error: ' +
                    (e.response.data?.message ||
                      JSON.stringify(e.response.data))
                )
              } else if (e.request) {
                alert('Failed to login, no response from server.')
              } else {
                alert('Failed to login, error: ' + e.message)
              }
            }
          }}
        >
          <input
            id='username'
            name='username'
            placeholder='Username'
            type='username'
            value={username}
            onChange={e => setUsername(e.target.value)}
            required
          />
          <input
            id='password'
            name='password'
            placeholder='Password'
            type='password'
            value={password}
            onChange={e => setPassword(e.target.value)}
            required
          />
          <button type='submit'>Login</button>
        </form>
      )}
    </div>
  )
}

export default function LoginPage () {
  return (
    <Suspense
      fallback={<p className='px-8 -mt-2 -mb-2 text-center'>Loading...</p>}
    >
      <LoginPageWithParams />
    </Suspense>
  )
}

function LoginPageWithParams () {
  const params = useSearchParams()
  const redirect = params.get('redirect')

  return <LoginForm redirect={redirect} />
}
