import PageContent from '~/modules/page-content';
import RegistrasiIndividu from './components/RegistrasiIndividu';
import RegistrasiBisnis from './components/RegistrasiBisnis';
import Link from 'next/link';
import Image from 'next/image';
import IndoteknikLogo from '~/images/logo.png';
import AccountActivation from '../account-activation';
import { useMemo, useState } from 'react';
import { useRegisterStore } from './stores/useRegisterStore';
import FormCaptcha from './components/FormCaptcha';
import TermCondition from './components/TermCondition';
import { Button } from '@chakra-ui/react';
import { useMutation } from 'react-query';
import { UseToastOptions, useToast } from '@chakra-ui/react';
import { RegisterProps } from '~/types/auth';
import { registerUser } from '~/services/auth';
import { useRouter } from 'next/router';

const LOGO_WIDTH = 150;
const LOGO_HEIGHT = LOGO_WIDTH / 3;

const Register = () => {
  const [isIndividuClicked, setIsIndividuClicked] = useState(true);
  const [notValid, setNotValid] = useState(false);
  const [buttonSubmitClick, setButtonSubmitClick] = useState(false);
  const [isBisnisClicked, setIsBisnisClicked] = useState(false);
  const { form, isCheckedTNC, isValidCaptcha, resetForm, errors, updateForm } =
    useRegisterStore();

  const isFormValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
  const toast = useToast();
  const router = useRouter();
  const mutation = useMutation({
    mutationFn: (data: RegisterProps) => registerUser(data),
  });

  const handleIndividuClick = () => {
    resetForm();
    setIsIndividuClicked(true);
    setIsBisnisClicked(false);
  };

  const handleBisnisClick = () => {
    resetForm();
    updateForm('is_terdaftar', 'false');
    updateForm('type_acc', 'business');
    setIsIndividuClicked(false);
    setIsBisnisClicked(true);
  };
  const handleSubmit = async () => {
    if (!isFormValid) {
      setNotValid(true);
      setButtonSubmitClick(!buttonSubmitClick);
      return;
    } else {
      setButtonSubmitClick(!buttonSubmitClick);
      setNotValid(false);
    }
    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,
      position: 'top',
    };

    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 (
    <div className='container'>
      <div className='grid grid-cols-1 md:grid-cols-2 gap-x-8 pt-10 px-2 md:pt-16'>
        <section className=''>
          <div className='px-8 py-4 border'>
            <Link href='/' className='block md:hidden'>
              <Image
                src={IndoteknikLogo}
                alt='Logo Indoteknik'
                width={LOGO_WIDTH}
                height={LOGO_HEIGHT}
                className='mx-auto mb-4 w-auto h-auto'
                priority
              />
            </Link>

            <h1 className='text-2xl font-semibold text-center md:text-left'>
              Daftar Akun Indoteknik
            </h1>
            <h2 className='text-gray_r-11 mt-1 mb-4 text-center md:text-left'>
              Buat akun sekarang lebih mudah dan terverifikasi
            </h2>

            <label htmlFor='name' className='text-black font-bold'>
              Tipe Akun
            </label>
            <div className='grid grid-cols-2 gap-x-3 mt-2 h-14 font-bold text-black hover:cursor-pointer'>
              <div
                className={` border rounded-md flex justify-center items-center transition-colors duration-300 ease-in-out ${
                  isIndividuClicked ? 'bg-red-500 text-white' : ''
                }`}
                onClick={handleIndividuClick}
              >
                <p>Individu</p>
              </div>
              <div
                className={` border rounded-md flex justify-center items-center transition-colors duration-300 ease-in-out ${
                  isBisnisClicked ? 'bg-red-500 text-white' : ''
                }`}
                onClick={handleBisnisClick}
              >
                <p>Bisnis</p>
              </div>
            </div>
            <div className='transition-opacity duration-300 ease-in-out'>
              {isIndividuClicked && (
                <div className='opacity-100'>
                  <RegistrasiIndividu
                    chekValid={notValid}
                    buttonSubmitClick={buttonSubmitClick}
                  />
                </div>
              )}
              {isBisnisClicked && (
                <div className='opacity-100'>
                  <RegistrasiBisnis
                    chekValid={notValid}
                    buttonSubmitClick={buttonSubmitClick}
                  />
                </div>
              )}
            </div>
            <section className='mt-2'>
              {/* <FormCaptcha /> */}
              <TermCondition />
              <Button
                type='submit'
                colorScheme='red'
                className='w-full mt-2'
                size='lg'
                onClick={handleSubmit}
                // isDisabled = {!isFormValid || !isCheckedTNC || mutation.isLoading || !isValidCaptcha}
                isDisabled={!isCheckedTNC || mutation.isLoading}
              >
                {mutation.isLoading ? 'Loading...' : 'Daftar'}
              </Button>
            </section>
            <section className='flex justify-center items-center flex-col'>
              <div className='text-gray_r-11 mt-4 text-center md:text-left'>
                Sudah punya akun Indoteknik?{' '}
                <Link
                  href='/login'
                  className='inline font-medium text-danger-500'
                >
                  Masuk
                </Link>
              </div>
              <div className='text-gray_r-11 mt-4 text-center md:text-left'>
                Akun anda belum aktif?{' '}
                <Link
                  href='/register?activation=email'
                  className='inline font-medium text-danger-500'
                >
                  Aktivasi
                </Link>
              </div>
            </section>
          </div>
        </section>

        <section className='my-10 md:my-0'>
          <PageContent path='/register' />
        </section>
      </div>

      <AccountActivation />
    </div>
  );
};

export default Register;
