'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'
import Link from 'next/link'
import { BackButton } from '@/app/components/BackButton'

function AccountLoginForm ({ redirect }: { redirect: string | null }) {
  const [loading, setLoading] = useState<boolean>(true)
  const [alreadyLoggedIn, setAlreadyLoggedIn] = useState<boolean>(false)
  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') {
      document.title = 'Lncvrt Games - Account Login'
      setAlreadyLoggedIn(true)
    }
    setLoading(false)
  }, [router])

  return (
    <div className='box'>
      {alreadyLoggedIn ? <BackButton href='/account' /> : <HomeButton />}
      <DiscordButton />
      <p className={`px-8 ${loading ? '-my-2' : 'mb-4 -mt-2'} text-center`}>
        {loading
          ? 'Loading...'
          : `Lncvrt Games ${alreadyLoggedIn ? 'Refresh ' : ''}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 ${
                      alreadyLoggedIn ? 'refresh ' : ''
                    }login, error: ` + (result.data.message || 'n/a')
                  )
                }
              } catch (e: any) {
                if (e.response) {
                  alert(
                    `Failed to ${
                      alreadyLoggedIn ? 'refresh ' : ''
                    }login, error: ` +
                      (e.response.data?.message ||
                        JSON.stringify(e.response.data))
                  )
                } else if (e.request) {
                  alert(
                    `Failed to ${
                      alreadyLoggedIn ? 'refresh ' : ''
                    }login, no response from server.`
                  )
                } else {
                  alert(
                    `Failed to ${
                      alreadyLoggedIn ? 'refresh ' : ''
                    }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>
          <p
            className='my-2 w-60 whitespace-normal text-center text-sm'
            hidden={alreadyLoggedIn}
          >
            Note: You login here with your Lncvrt Games Account. If you played
            Berry Dash version 1.8.2 or older, then you login with that account
            here. It has been migrated automatically.
          </p>
          <div
            className='flex justify-center flex-col gap-2 mt-6 text-center'
            hidden={alreadyLoggedIn}
          >
            <Link
              href='/account/forgot-username'
              draggable={false}
              className='button'
            >
              Forgot username?
            </Link>
            <Link
              href='/account/forgot-password'
              draggable={false}
              className='button'
            >
              Forgot password?
            </Link>
            <Link href='/account/register' draggable={false} className='button'>
              Don&apos;t have an account?
            </Link>
          </div>
        </>
      )}
    </div>
  )
}

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

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

  return <AccountLoginForm redirect={redirect} />
}
