import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { GetServerSideProps, NextPage } from 'next';
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { LockOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { Button, Form, Input } from 'antd';
import PasswordHintContainer from '@/components/ui/input/password/PasswordHintContainer';
import { checkResetToken, resetPassword } from '@/services/auth';
import { AxiosErrorResponse, BasePageProps } from '@/types';
import { errorMessageFormatter } from '@/utils/errorFormatter';
import { passwordRegex } from '@/utils/regex';
import logo from '../../../../public/logo.png';

interface ResetPasswordPageProps extends BasePageProps {
    token: string;
}

const ResetPasswordPage: NextPage<ResetPasswordPageProps> = ({ member, token }) => {
    const { t } = useTranslation(['auth', 'messages']);
    const [resetPasswordForm] = Form.useForm();
    const [password, setPassword] = useState<string>('');
    const router = useRouter();

    useEffect(() => {
        resetPasswordForm.setFieldsValue({
            email: member.email,
        });
    }, []);

    // Mutations
    const resetPasswordMutation = useMutation({
        mutationFn: async (password: string) => {
            const response = await resetPassword(member.id, token, password);
            return response.data;
        },
        onSuccess: () => {
            setTimeout(() => {
                router.push('/');
            }, 2000);
        },
    });

    // Handlers
    const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setPassword(e.target.value);
    };

    const onSubmitHandler = () => {
        resetPasswordForm.validateFields().then(async (values) => {
            toast.promise(resetPasswordMutation.mutateAsync(values.password), {
                pending: t('messages:resetting-password'),
                success: t('messages:password-reset-success'),
                error: {
                    render({ data }) {
                        return t(errorMessageFormatter(data as AxiosErrorResponse));
                    },
                },
            });
        });
    };

    return (
        <div className="flex items-center justify-center h-screen">
            <div className="w-full max-w-[500px] px-5">
                <div className="relative mb-8 w-full text-center md:px-10">
                    <Image src={logo} priority={true} alt="Logo" style={{ width: '200px', height: 'auto' }}></Image>
                </div>
                <div>
                    <Form form={resetPasswordForm} layout="vertical" size="large">
                        <Form.Item label={t('email')} name="email" className="mb-5" labelCol={{ flex: '35px' }}>
                            <Input disabled />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            label={t('password')}
                            rules={[
                                { required: true },
                                {
                                    pattern: passwordRegex,
                                    message: '',
                                },
                            ]}
                            className="mb-5"
                            labelCol={{ flex: '35px' }}
                        >
                            <Input.Password classNames={{ prefix: '!me-2' }} prefix={<LockOutlined />} onChange={handlePasswordChange} />
                        </Form.Item>
                        <Form.Item
                            name="confirmPassword"
                            label={t('confirm-password')}
                            dependencies={['password']}
                            rules={[
                                { required: true },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error(t('password-not-match')));
                                    },
                                }),
                            ]}
                            className="mb-5"
                            labelCol={{ flex: '35px' }}
                        >
                            <Input.Password classNames={{ prefix: '!me-2' }} prefix={<LockOutlined />} />
                        </Form.Item>
                        <PasswordHintContainer password={password} />
                        <Button
                            type="primary"
                            htmlType="submit"
                            block
                            className="mt-3"
                            loading={resetPasswordMutation.isLoading}
                            onClick={onSubmitHandler}
                        >
                            {t('submit')}
                        </Button>
                    </Form>
                </div>
            </div>
        </div>
    );
};

export default ResetPasswordPage;

export const getServerSideProps: GetServerSideProps = async ({ locale, params }) => {
    try {
        const checkTokenResponse = await checkResetToken(params!.memberId as string, params!.token as string);

        return {
            props: {
                member: checkTokenResponse.data,
                token: params!.token,
                ...(await serverSideTranslations(locale as string, ['auth', 'messages', 'api-messages'])),
            },
        };
    } catch (error: unknown) {
        return {
            redirect: {
                destination: '/404',
                permanent: false,
            },
        };
    }
};
