import React from 'react';
import type { ReactElement } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import Head from 'next/head';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import { Field, Form, Formik } from 'formik';
import FormField from '../components/FormField';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import { requestEmailOtp, setAuthToken, verifyEmailOtp } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';

import axios from "axios";

export default function Register() {
    const [loading, setLoading] = React.useState(false);
    const [otpEmail, setOtpEmail] = React.useState('');
    const [otpCode, setOtpCode] = React.useState('');
    const [otpRequested, setOtpRequested] = React.useState(false);
    const router = useRouter();
    const dispatch = useAppDispatch();
    const { isFetching, isRequestingOtp } = useAppSelector((state) => state.auth);
    const notify = (type, msg) => toast( msg, {type, position: "bottom-center"});

    React.useEffect(() => {
        const redirectToken = router.query.token;

        if (typeof redirectToken === 'string') {
            dispatch(setAuthToken(redirectToken));
            router.replace('/dashboard');
        }
    }, [dispatch, router, router.query.token]);

    const handleGoogleSignin = () => {
        if (typeof window === 'undefined') {
            return;
        }

        window.location.href = `/api/auth/signin/google?app=${encodeURIComponent(window.location.origin)}`;
    };

    const handleRequestOtp = async () => {
        const email = otpEmail.trim();

        if (!email) {
            notify('error', 'Masukkan email terlebih dahulu');
            return;
        }

        const result = await dispatch(requestEmailOtp({ email }));

        if (requestEmailOtp.fulfilled.match(result)) {
            setOtpRequested(true);
            notify('success', 'Kode OTP sudah dikirim ke email Anda');
            return;
        }

        notify('error', String(result.payload || 'Gagal mengirim OTP'));
    };

    const handleVerifyOtp = async () => {
        const email = otpEmail.trim();
        const otp = otpCode.trim();

        if (!email || !otp) {
            notify('error', 'Masukkan email dan kode OTP');
            return;
        }

        const result = await dispatch(verifyEmailOtp({ email, otp }));

        if (verifyEmailOtp.fulfilled.match(result)) {
            notify('success', 'Akun Anggota berhasil dibuat/masuk');
            await router.push('/dashboard');
            return;
        }

        notify('error', String(result.payload || 'Kode OTP tidak valid'));
    };

    const handleSubmit = async (value) => {
        setLoading(true)
        try {
            
            const { data: response } = await axios.post('/auth/signup',value);
            await router.push('/login')
            setLoading(false)
            notify('success', 'Please check your email for verification link')
        } catch (error) {
            setLoading(false)
            console.log('error: ', error)
            notify('error', 'Something was wrong. Try again')
        }
    };

    return (
        <>
            <Head>
                <title>{getPageTitle('Register')}</title>
            </Head>

            <SectionFullScreen bg='violet'>
                <CardBox className='w-11/12 md:w-7/12 lg:w-6/12 xl:w-4/12'>
                    <div className='mb-6 rounded-xl border border-blue-100 bg-blue-50/70 p-4 dark:border-dark-700 dark:bg-dark-800'>
                        <h2 className='mb-2 text-2xl font-semibold text-gray-800 dark:text-white'>Daftar Anggota</h2>
                        <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
                            Pendaftar baru lewat Google atau Email OTP otomatis mendapat role Anggota. Admin dibuat/diubah manual oleh admin utama.
                        </p>
                        <BaseButtons type='justify-start' mb='mb-4'>
                            <BaseButton
                                className='w-full'
                                label='Daftar / Masuk dengan Google'
                                color='info'
                                onClick={handleGoogleSignin}
                            />
                        </BaseButtons>

                        <div className='rounded-lg bg-white/80 p-4 dark:bg-dark-900'>
                            <FormField label='Email OTP' help='Masukkan email untuk menerima kode OTP'>
                                <input
                                    type='email'
                                    value={otpEmail}
                                    onChange={(event) => setOtpEmail(event.target.value)}
                                    placeholder='nama@email.com'
                                />
                            </FormField>
                            {otpRequested && (
                                <FormField label='Kode OTP' help='Masukkan 6 digit kode dari email'>
                                    <input
                                        inputMode='numeric'
                                        maxLength={6}
                                        value={otpCode}
                                        onChange={(event) => setOtpCode(event.target.value.replace(/\D/g, '').slice(0, 6))}
                                        placeholder='123456'
                                    />
                                </FormField>
                            )}
                            <BaseButtons type='justify-start'>
                                <BaseButton
                                    label={isRequestingOtp ? 'Mengirim...' : otpRequested ? 'Kirim Ulang OTP' : 'Kirim OTP'}
                                    color='info'
                                    outline
                                    disabled={isRequestingOtp}
                                    onClick={handleRequestOtp}
                                />
                                {otpRequested && (
                                    <BaseButton
                                        label={isFetching ? 'Memverifikasi...' : 'Verifikasi OTP'}
                                        color='success'
                                        disabled={isFetching}
                                        onClick={handleVerifyOtp}
                                    />
                                )}
                            </BaseButtons>
                        </div>

                        <BaseDivider />
                        <p className='text-center text-xs text-gray-500'>Atau gunakan form password legacy di bawah ini.</p>
                    </div>
                    <Formik
                        initialValues={{
                            email: '',
                            password: '',
                            confirm: ''
                        }}
                        onSubmit={(values) => handleSubmit(values)}
                    >
                        <Form>
                         
                            <FormField label='Email' help='Please enter your email'>
                                <Field type='email' name='email' />
                            </FormField>
                            <FormField label='Password' help='Please enter your password'>
                                <Field type='password' name='password' />
                            </FormField>
                            <FormField label='Confirm Password' help='Please confirm your password'>
                                <Field type='password' name='confirm' />
                            </FormField>

                            <BaseDivider />

                            <BaseButtons>
                                <BaseButton
                                    type='submit'
                                    label={loading ? 'Loading...' : 'Register' }
                                    color='info'
                                />
                                <BaseButton
                                    href={'/login'}
                                    label={'Login'}
                                    color='info'
                                />
                            </BaseButtons>
                        </Form>
                    </Formik>
                </CardBox>
            </SectionFullScreen>
            <ToastContainer />
        </>
    );
}

Register.getLayout = function getLayout(page: ReactElement) {
    return <LayoutGuest>{page}</LayoutGuest>;
};
