import { 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 Link from 'next/link';
import { useRouter } from 'next/router';
import { LockOutlined, MailOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { Button, Divider, Form, Input, Modal } from 'antd';
import { forgotPassword, login } from '@/services/auth';
import { ForgotPasswordErrorResponse, LoginErrorResponse, LoginParams } from '@/types';
import { AxiosErrorResponse } from '@/types';
import { authentication } from '@/utils/authentication';
import { errorMessageFormatter } from '@/utils/errorFormatter';
import localeLinkGenerator from '@/utils/localeLinkGenerator';
import Logo from '../../public/logo.png';
import Image from 'next/image';

const LoginPage: NextPage = () => {
    const { t } = useTranslation(['auth', 'common', 'messages', 'api-messages']);
    const router = useRouter();
    const [loginForm] = Form.useForm();
    const [forgotPasswordForm] = Form.useForm();
    const [forgotPasswordModalOpen, setForgotPasswordModalOpen] = useState(false);

    // Mutations
    const loginMutation = useMutation({
        mutationFn: async (loginCredentials: LoginParams) => {
            const { data } = await login(loginCredentials);
            return data;
        },
        onSuccess: () => {
            if (router.query.redirect) {
                router.push(router.query.redirect as string);
                return;
            }
            router.push('/dashboard');
        },
        onError: (error: LoginErrorResponse) => {
            if (error.response?.data?.unverified) {
                router.push(`/?unverified=true&email=${loginForm.getFieldValue('email')}`);
            }
        },
    });

    const forgotPasswordMutation = useMutation({
        mutationFn: async (email: string) => {
            const res = await forgotPassword(email);
            return res.data;
        },
        onSuccess: () => {
            forgotPasswordForm.resetFields();
            setForgotPasswordModalOpen(false);
        },
        onError: (error: ForgotPasswordErrorResponse) => {
            if (error.response?.data?.unverified) {
                // Reload the page with ?unverified=true&email={email}
                // to show the verification message
                router.push(`/?unverified=true&email=${forgotPasswordForm.getFieldValue('email')}`);
            }
            setForgotPasswordModalOpen(false);
        },
    });

    // Handlers
    const onLoginHandler = () => {
        loginForm.validateFields().then((values) => {
            toast.promise(loginMutation.mutateAsync(values), {
                pending: t('messages:logging-in'),
                success: t('messages:logged-in'),
                error: {
                    render({ data }) {
                        return t(errorMessageFormatter(data as AxiosErrorResponse));
                    },
                },
            });
        });
    };

    const onForgotPasswordCancelHandler = () => {
        forgotPasswordForm.resetFields();
        setForgotPasswordModalOpen(false);
    };

    const onForgotPasswordHandler = () => {
        forgotPasswordForm.validateFields().then(async (values) => {
            toast.promise(forgotPasswordMutation.mutateAsync(values.email), {
                pending: t('messages:sending-reset-password-email'),
                success: t('messages:reset-password-email-sent'),
                error: {
                    render({ data }) {
                        return t(errorMessageFormatter(data as AxiosErrorResponse));
                    },
                },
            });
        });
    };

    return (
        <div className="flex items-center justify-center h-screen loginBackground">
            <div className="w-full max-w-[500px] px-5">
                <div className="relative mb-6 w-full text-center md:px-10">
                    <Image src={Logo} alt="Logo" style={{ width: '180px', height: 'auto' }} />
                </div>
                <div>
                    <h1 className="text-2xl text-center font-semibold mb-6">{t('signin-title')}</h1>
                    {/* L Form */}
                    <Form form={loginForm} layout="vertical" size="large">
                        {/* L - Email Input */}
                        <Form.Item
                            label={t('email')}
                            name="email"
                            rules={[{ required: true }, { type: 'email' }]}
                            className="mb-5"
                            labelCol={{ flex: '35px' }}
                        >
                            <Input classNames={{ prefix: '!me-2' }} prefix={<MailOutlined className="site-form-item-icon" />} />
                        </Form.Item>
                        {/* L- Password Input */}
                        <Form.Item label={t('password')} name="password" rules={[{ required: true }]} className="mb-1" labelCol={{ flex: '35px' }}>
                            <Input.Password classNames={{ prefix: '!me-2' }} prefix={<LockOutlined className="site-form-item-icon" />} />
                        </Form.Item>
                        <Form.Item className="mt-4 mb-1">
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="mt-3"
                                block
                                onClick={onLoginHandler}
                                loading={loginMutation.isLoading}
                            >
                                {t('login')}
                            </Button>
                        </Form.Item>
                    </Form>
                    <div className="text-[12px] cursor-pointer hover:text-[#14aafd] mt-2" onClick={() => setForgotPasswordModalOpen(true)}>
                        {t('forgot-password')}
                    </div>
                </div>
                <Divider />
                <p className="text-center">
                    {t('dont-have-an-account')} <Link href="/register">{t('register-now')}</Link>
                </p>
            </div>
            {/* Forget Password Modal */}
            <Modal
                title={t('forgot-password')}
                open={forgotPasswordModalOpen}
                onCancel={onForgotPasswordCancelHandler}
                classNames={{
                    mask: 'w-screen h-screen !bg-[#00000026] backdrop-blur backdrop-saturate-150',
                }}
                footer={null}
            >
                <p className="mt-3 text-sm">{t('forgot-password-message')}</p>
                {/* FP Form */}
                <Form form={forgotPasswordForm} layout="vertical" size="large" className="mt-4">
                    {/* FP - Email Input */}
                    <Form.Item
                        label={t('email')}
                        name="email"
                        rules={[
                            {
                                required: true,
                            },
                            { type: 'email' },
                        ]}
                        className="mb-1"
                        labelCol={{ flex: '35px' }}
                    >
                        <Input classNames={{ prefix: '!me-2' }} prefix={<MailOutlined className="site-form-item-icon" />} />
                    </Form.Item>
                    <div className="flex gap-4 mt-6 mb-1">
                        {/* FP - Cancel Button */}
                        <Form.Item noStyle>
                            <Button type="default" block onClick={onForgotPasswordCancelHandler} loading={forgotPasswordMutation.isLoading}>
                                {t('cancel')}
                            </Button>
                        </Form.Item>
                        {/* FP - Reset Password Button */}
                        <Form.Item noStyle>
                            <Button
                                type="primary"
                                htmlType="submit"
                                block
                                onClick={onForgotPasswordHandler}
                                loading={forgotPasswordMutation.isLoading}
                            >
                                {t('reset-password')}
                            </Button>
                        </Form.Item>
                    </div>
                </Form>
            </Modal>
        </div>
    );
};

export default LoginPage;

export const getServerSideProps: GetServerSideProps = async ({ req, locale }) => {
    try {
        await authentication(req);

        return {
            redirect: {
                destination: localeLinkGenerator(locale, '/dashboard'),
                permanent: false,
                locale,
            },
        };
    } catch (error) {
        return {
            props: {
                ...(await serverSideTranslations(locale as string, ['auth', 'common', 'messages', 'api-messages'])),
            },
        };
    }
};
