import { Alert, AlertIcon } from "@chakra-ui/react"
import Link from "next/link"
import { useRouter } from "next/router"
import { ChangeEvent, useEffect, useState } from "react"
import { useMutation } from "react-query"
import Modal from "~/common/components/elements/Modal"
import { useRegisterStore } from "~/common/stores/useRegisterStore"
import { ActivationReqProps } from "~/common/types/auth"
import { activationReq } from "~/services/auth"

const FormEmail = () => {
  const router = useRouter()
  const { query } = router
  const [active, setActive] = useState<boolean>(false)
  const [isBtnDisabled, setIsBtnDisabled] = useState<boolean>(true)
  const [email, setEmail] = useState<string>('')

  const { form } = useRegisterStore()

  useEffect(() => {
    if (form) setEmail(form?.email)
  }, [form])

  useEffect(() => {
    setIsBtnDisabled(email === '')
  }, [email])

  useEffect(() => {
    setActive(query?.activation === 'email')
  }, [query.activation])

  const mutation = useMutation({
    mutationFn: (data: ActivationReqProps) => activationReq(data)
  })

  const handleSubmit = (e: ChangeEvent<HTMLFormElement>) => {
    e.preventDefault()
    mutation.data = undefined
    mutation.mutate({ email })
  }

  useEffect(() => {
    if (mutation.data?.activation_request === true) {
      const urlParams = new URLSearchParams({
        activation: 'otp',
        email
      })
      router.push(`${router.route}?${urlParams}`)
    }
  }, [mutation.data?.activation_request, router, email])

  return (
    <Modal active={active} mode="desktop" close={() => router.push(router.route)} title="Aktivasi Akun">
      <form onSubmit={handleSubmit} className="py-3 flex flex-col items-center gap-y-4">
        {
          mutation.data !== undefined &&
          !mutation.data?.activation_request &&
          (
            <Alert status="warning">
              <AlertIcon />
              {mutation.data?.reason === 'ACTIVE' && 'Akun sudah aktif.'}
              {mutation.data?.reason === 'NOT_FOUND' && 'Akun tidak ditemukan.'}

              {mutation.data?.reason === 'ACTIVE' && (
                <Link href="/login" className="ml-1 text-yellow-700 underline">Klik untuk masuk akun anda</Link>
              )}

              {mutation.data?.reason === 'NOT_FOUND' && (
                <Link href="/register" className="ml-1 text-yellow-700 underline">Klik untuk daftar akun baru</Link>
              )}
            </Alert>
          )
        }

        <input
          type="text"
          className="form-input w-full"
          placeholder="Masukan alamat email anda"
          autoComplete="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          autoFocus
        />
        <button
          type="submit"
          className="btn-yellow w-full"
          disabled={isBtnDisabled || mutation.isLoading}
        >
          {mutation.isLoading ? 'Loading...' : 'Kirim Aktivasi'}
        </button>
      </form>
    </Modal>
  )
}

export default FormEmail