import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import IndoteknikLogo from '@/images/logo.png'
import axios from 'axios'
import { setAuth } from '@/core/utils/auth'
import Alert from '@/core/components/elements/Alert/Alert'
import odooApi from '@/core/api/odooApi'

const Activate = () => {
  const router = useRouter()
  const { token } = router.query

  const [isLoading, setIsLoading] = useState(false)
  const [alert, setAlert] = useState()

  const [email, setEmail] = useState(router.query?.email || '')

  useEffect(() => {
    const activateIfTokenExist = async () => {
      if (token) {
        let isActivated = await odooApi('POST', '/api/v1/user/activation', { token })
        if (isActivated.activation) {
          setAuth(isActivated.user)
          setAlert({
            children: (
              <>
                Selamat, akun anda berhasil diaktifkan,{' '}
                <Link
                  className='text-gray_r-12'
                  href='/'
                >
                  kembali ke beranda
                </Link>
                .
              </>
            ),
            type: 'success'
          })
        } else {
          setAlert({
            children: (
              <>
                Mohon maaf token sudah tidak aktif, lakukan permintaan aktivasi akun kembali atau{' '}
                <Link
                  className='text-gray_r-12'
                  href='/login'
                >
                  masuk
                </Link>{' '}
                jika sudah memiliki akun.
              </>
            ),
            type: 'info'
          })
        }
      }
    }
    activateIfTokenExist()
  }, [token])

  useEffect(() => {
    if (router.query.email) setEmail(router.query.email)
  }, [router])

  const activationRequest = async (e) => {
    e.preventDefault()
    setIsLoading(true)
    let activationRequest = await axios.post(`${process.env.NEXT_PUBLIC_SELF_HOST}/api/activation-request`, {
      email
    })
    if (activationRequest.data.activationRequest) {
      setAlert({
        children: <>Mohon cek email anda untuk aktivasi akun Indoteknik</>,
        type: 'success'
      })
    } else {
      switch (activationRequest.data.reason) {
        case 'NOT_FOUND':
          setAlert({
            children: (
              <>
                Email tersebut belum terdaftar,{' '}
                <Link
                  className='text-gray_r-12'
                  href='/register'
                >
                  daftar sekarang
                </Link>
                .
              </>
            ),
            type: 'info'
          })
          break
        case 'ACTIVE':
          setAlert({
            children: (
              <>
                Email tersebut sudah terdaftar dan sudah aktif,{' '}
                <Link
                  className='text-gray_r-12'
                  href='/login'
                >
                  masuk sekarang
                </Link>
                .
              </>
            ),
            type: 'info'
          })
          break
      }
    }
    setIsLoading(false)
  }

  return (
    <div className='p-6 pt-10 flex flex-col items-center min-h-screen'>
      <Link href='/'>
        <Image
          src={IndoteknikLogo}
          alt='Logo Indoteknik'
          width={150}
          height={50}
        />
      </Link>

      <h1 className='text-2xl mt-4 font-semibold'>Aktivasi Akun Indoteknik</h1>

      {alert && (
        <Alert
          className='text-center mt-4'
          type={alert.type}
        >
          {alert.children}
        </Alert>
      )}

      <form
        onSubmit={activationRequest}
        className='mt-6 w-full'
      >
        <input
          type='email'
          id='email'
          className='form-input w-full text-center'
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder='Masukan alamat email'
          autoFocus
        />
        <button
          type='submit'
          disabled={email != ''}
          className='btn-yellow font-semibold mt-4 w-full'
        >
          {isLoading ? 'Loading...' : 'Aktivasi'}
        </button>
      </form>
    </div>
  )
}

export default Activate
