import { Alert, AlertDescription, AlertIcon, AlertTitle, Spinner } from "@chakra-ui/react"
import { useRouter } from "next/router"
import { useEffect, useState } from "react"
import Link from "next/link"
import { useMutation } from "react-query"

import Modal from "~/common/components/elements/Modal"
import { ActivationTokenProps } from "~/common/types/auth"
import { activationUserToken } from "~/services/auth"
import { setAuth } from "~/common/libs/auth"

const FormToken = () => {
  const router = useRouter()
  const { query } = router
  const [active, setActive] = useState<boolean>(false)

  const mutation = useMutation({
    mutationFn: (data: ActivationTokenProps) => activationUserToken(data),
  })

  useEffect(() => {
    if (query?.activation === 'token' && typeof query?.token === 'string') {
      mutation.mutate({ token: query.token })
      setActive(true)
    }
    //eslint-disable-next-line
  }, [query.activation, query.token])

  useEffect(() => {
    if (mutation.data?.user) {
      setAuth(mutation.data.user)
      router.push((query?.redirect || '/') as string)
    }
  }, [mutation.data, router, query.redirect])

  return (
    <Modal active={active} mode="desktop">
      <div className="pb-6 flex flex-col items-center gap-y-6">
        {mutation.isLoading && (
          <>
            <Spinner size='lg' borderWidth='3px' />
            <div className="text-h-sm">Mohon tunggu sedang memverifikasi akun</div>
          </>
        )}

        {!mutation.isLoading && !mutation.data?.activation && (
          <Alert
            status={mutation.data?.activation ? 'success' : 'error'}
            flexDirection="column"
            alignItems="center"
            justifyContent="center"
            textAlign="center"
            height="200px"
            bg="transparent"
          >
            <AlertIcon boxSize="40px" mr={0} />
            <AlertTitle className="mt-4 mb-1 text-h-sm">
              Aktivasi akun gagal
            </AlertTitle>
            <AlertDescription maxWidth="sm">
              {mutation.data?.reason === 'INVALID_TOKEN' && (
                <>
                  Token sudah kadaluwarsa, silahkan coba kembali.
                  <Link href='/register?activation=email' className="block mt-8 text-red-700 underline">Aktivasi Akun</Link>
                </>
              )}
            </AlertDescription>
          </Alert>
        )}
      </div>
    </Modal>
  )
}

export default FormToken