import React from 'react';
import {toast, ToastContainer} from 'react-toastify';

import Head from 'next/head';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import {useRouter} from 'next/router';
import {getPageTitle} from '../config';

import {Field, Form, Formik} from 'formik';
import FormField from '../components/FormField';
import BaseButtons from '../components/BaseButtons';
import BaseButton from '../components/BaseButton';
import { passwordReset } from '../stores/authSlice';
import {useAppDispatch} from '../stores/hooks';

type PasswordValues = {
    password: string;
    confirm: string;
};

export default function PasswordSetOrReset() {
    const [loading, setLoading] = React.useState(false);
    const [isInvitation, setIsInvitation] =  React.useState(false);
    const router = useRouter();
    const {token, invitation} = router.query;

    const dispatch = useAppDispatch();
    
    React.useEffect(() => {
        if (invitation) {
          setIsInvitation(true);
        }
      }, [invitation]);

    const handleSubmit = async (value: PasswordValues) => {
        setLoading(true);
        try {
            if (typeof token !== 'string') {
                throw new Error('Password reset token is missing.');
            }

            await dispatch(
                passwordReset({
                    token,
                    password: value.password,
                    type: isInvitation && 'invitation',
                }),
            ).unwrap();
            await router.push('/login');
        } catch (error) {
            const message = error instanceof Error ? error.message : 'Password could not be saved.';
            toast.error(message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <Head>
                {isInvitation && <title>{getPageTitle('Set Password')}</title>}
                {!isInvitation && <title>{getPageTitle('Reset Password')}</title>}
            </Head>

            <SectionFullScreen bg='violet'>
                <div className='w-full flex flex-col items-center justify-center'>
                    <CardBox className='w-11/12 md:w-7/12 lg:w-6/12 xl:w-4/12'>
                        {isInvitation && <p className='text-xl mb-2'>Set Password</p>}
                        {!isInvitation && <p className='text-xl mb-2'>Reset Password</p>}
                        <p className='text-base mb-4'>Enter your new password</p>

                        <Formik
                            initialValues={{
                                password: '',
                                confirm: '',
                            }}
                            validate={(values: PasswordValues) => {
                                const errors: Partial<Record<keyof PasswordValues, string>> = {};
                                if (values.password.length < 12) {
                                    errors.password = 'Use at least 12 characters.';
                                }
                                if (values.confirm !== values.password) {
                                    errors.confirm = 'Passwords must match.';
                                }
                                return errors;
                            }}
                            onSubmit={(values) => handleSubmit(values)}
                        >
                            {({errors, touched}) => (
                                <Form>
                                    <FormField
                                    >
                                        <Field
                                            type='password'
                                            name='password'
                                            placeholder='Password'
                                            autoComplete='new-password'
                                            aria-describedby='password-error'
                                        />
                                    </FormField>
                                    {touched.password && errors.password && <p id='password-error' role='alert' className='-mt-4 mb-4 text-sm text-red-600'>{errors.password}</p>}
                                    <FormField
                                    >
                                        <Field
                                            type='password'
                                            name='confirm'
                                            placeholder='Confirm Password'
                                            autoComplete='new-password'
                                            aria-describedby='confirm-password-error'
                                        />
                                    </FormField>
                                    {touched.confirm && errors.confirm && <p id='confirm-password-error' role='alert' className='-mt-4 mb-4 text-sm text-red-600'>{errors.confirm}</p>}

                                    <BaseButtons>
                                        <BaseButton
                                            className='w-full mt-3'
                                            type='submit'
                                            disabled={loading}
                                            label={
                                                loading
                                                    ? 'Loading...'
                                                    : isInvitation
                                                        ? 'Set Password'
                                                        : 'Reset Password'
                                            }
                                            color='info'
                                        />
                                    </BaseButtons>
                                </Form>
                            )}
                        </Formik>
                    </CardBox>
                </div>
            </SectionFullScreen>
            <ToastContainer/>
        </>
    );
}
