import { ChangeEvent, useEffect } from "react";
import { useMutation } from "react-query";
import { useRegisterStore } from "~/common/stores/useRegisterStore";
import { RegisterProps } from "~/common/types/auth";
import { registerUser } from "~/services/auth";
import TermCondition from "./TermCondition";
import FormCaptcha from "./FormCaptcha";
import { useRouter } from "next/router";
import { UseToastOptions, useToast } from "@chakra-ui/react";
import Link from "next/link";
import { registerSchema } from "~/common/validations/auth";

const Form = () => {
  const {
    form,
    isValid,
    isCheckedTNC,
    isValidCaptcha,
    errors,
    updateForm,
    validate,
  } = useRegisterStore()
  const router = useRouter()
  const toast = useToast()

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    updateForm(name, value)
    validate()
  }

  const mutation = useMutation({
    mutationFn: (data: RegisterProps) => registerUser(data)
  })

  const handleSubmit = async (e: ChangeEvent<HTMLFormElement>) => {
    e.preventDefault()

    const response = await mutation.mutateAsync(form)

    if (response?.register === true) {
      const urlParams = new URLSearchParams({
        activation: 'otp',
        email: form.email,
        redirect: (router.query?.next || '/') as string
      })
      router.push(`${router.route}?${urlParams}`)
    }

    const toastProps: UseToastOptions = {
      duration: 5000,
      isClosable: true
    }

    switch (response?.reason) {
      case 'EMAIL_USED':
        toast({
          ...toastProps,
          title: 'Email sudah digunakan',
          status: 'warning'
        })
        break;
      case 'NOT_ACTIVE':
        const activationUrl = `${router.route}?activation=email`
        toast({
          ...toastProps,
          title: 'Akun belum aktif',
          description: <>Akun sudah terdaftar namun belum aktif. <Link href={activationUrl} className="underline">Klik untuk aktivasi akun</Link></>,
          status: 'warning'
        })
        break
    }
  }

  return (
    <form className="mt-6 grid grid-cols-1 gap-y-4" onSubmit={handleSubmit}>
      <div>
        <label htmlFor="company">
          Nama Perusahaan <span className='text-gray_r-11'>(opsional)</span>
        </label>

        <input
          type="text"
          name="company"
          id="company"
          className="form-input mt-3"
          placeholder="cth: INDOTEKNIK DOTCOM GEMILANG"
          autoCapitalize="true"
          value={form.company}
          onChange={handleInputChange}
        />
      </div>

      <div>
        <label htmlFor='name'>Nama Lengkap</label>

        <input
          type='text'
          id='name'
          name='name'
          className='form-input mt-3'
          placeholder='Masukan nama lengkap anda'
          value={form.name}
          onChange={handleInputChange}
          aria-invalid={!!errors.name}
        />

        {!!errors.name && <span className="form-msg-danger">{errors.name}</span>}
      </div>

      <div>
        <label htmlFor='phone'>No Handphone</label>

        <input
          type='tel'
          id='phone'
          name='phone'
          className='form-input mt-3'
          placeholder='08xxxxxxxx'
          value={form.phone}
          onChange={handleInputChange}
          aria-invalid={!!errors.phone}
        />

        {!!errors.phone && <span className="form-msg-danger">{errors.phone}</span>}
      </div>

      <div>
        <label htmlFor='email'>Alamat Email</label>

        <input
          type='text'
          id='email'
          name='email'
          className='form-input mt-3'
          placeholder='Masukan alamat email anda'
          value={form.email}
          onChange={handleInputChange}
          autoComplete="username"
          aria-invalid={!!errors.email}
        />

        {!!errors.email && <span className="form-msg-danger">{errors.email}</span>}
      </div>

      <div>
        <label htmlFor='password'>Kata Sandi</label>
        <input
          type='password'
          name='password'
          id='password'
          className='form-input mt-3'
          placeholder='••••••••••••'
          value={form.password}
          onChange={handleInputChange}
          autoComplete="current-password"
          aria-invalid={!!errors.password}
        />

        {!!errors.password && <span className="form-msg-danger">{errors.password}</span>}
      </div>

      <FormCaptcha />

      <TermCondition />

      <button
        type="submit"
        className="btn-yellow w-full mt-2"
        disabled={!isValid || !isCheckedTNC || mutation.isLoading || !isValidCaptcha}
      >
        {mutation.isLoading ? 'Loading...' : 'Daftar'}
      </button>
    </form>
  )
}

export default Form