import { FC, useState } from 'react'
import LogoImage from '../../assets/images/logo.svg'
import LogoSmallImage from '../../assets/images/logo-small.svg'
import Input from '../../components/Input'
import { useTranslation } from 'react-i18next'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import Error from '../../components/Error'
import Button from '../../components/Button'
import { useLoginWithPassword } from './hooks/useAuthData'
import { ErrorType } from '../../helpers/types'
import { setRefreshToken, setToken, getRedirectUrl } from '../../config/func'
import { toast } from '../../components/Toast'
import { Paths } from '../../utils/Paths'

type LoginFormType = {
    email: string;
    password: string;
    twoFactorToken?: string;
}

const Login: FC = () => {
    const { t } = useTranslation('global')
    const loginWithPassword = useLoginWithPassword()
    const [showTwoFactor, setShowTwoFactor] = useState(false)

    const formik = useFormik<LoginFormType>({
        initialValues: {
            email: '',
            password: '',
            twoFactorToken: undefined,
        },
        validationSchema: Yup.object({
            email: Yup.string()
                .email(t('errors.invalid_email'))
                .required(t('errors.required')),
            password: Yup.string()
                .required(t('errors.required'))
        }),
        onSubmit(values) {
            loginWithPassword.mutate(values, {
                onSuccess(data) {
                    if (data?.data?.requires2FA) {
                        setShowTwoFactor(true)
                    } else {
                        setToken(data?.data?.accessToken?.token)
                        setRefreshToken(data?.data?.refreshToken?.token)
                        const redirectUrl = getRedirectUrl();
                        if (redirectUrl) {
                            window.location.href = redirectUrl;
                            return;
                        }
                        window.location.href = Paths.received
                    }
                },
                onError(error: ErrorType) {
                    toast(error?.response?.data?.error?.message[0], 'error')
                },
            })
        },
    })

    return (
        <div className='w-full h-full flex justify-center lg:py-[75px] py-4 lg:items-center lg:px-10 px-4'>
            <div className='flex w-full max-h-[812px] max-w-[1200px] bg-secondary h-full rounded-3xl overflow-hidden'>
                <div className='flex-1 min-w-[50%] overflow-y-auto bg-white lg:px-9 px-4 py-7'>
                    <div className='flex-1 h-full flex flex-col'>
                        <div className='flex relative flex-1 flex-col h-full justify-center'>
                            <img src={LogoSmallImage} className='w-8 hidden xl:block' />
                            <img src={LogoImage} className='w-44 right-0 left-0 mx-auto absolute top-10 xl:hidden' />

                            <div>
                                <div className='mt-5'>
                                    <h2 className='text-2xl font-bold'>
                                        {t('auth.welcome')}
                                    </h2>
                                    <p className='text-description text-sm mt-2'>
                                        {t('auth.enter_info_login')}
                                    </p>
                                </div>

                                <div className='mt-16 space-y-6'>
                                    <div>
                                        <Input
                                            label={t('auth.email')}
                                            placeholder={t('auth.enter_email')}
                                            type='email'
                                            className='text-right'
                                            name='email'
                                            onChange={formik.handleChange}
                                            value={formik.values.email}
                                        />
                                        {formik.touched.email && formik.errors.email && (
                                            <Error errorText={formik.errors.email} />
                                        )}
                                    </div>

                                    <div>
                                        <Input
                                            label={t('auth.password')}
                                            placeholder={t('auth.enter_password')}
                                            type='password'
                                            className='text-right'
                                            name='password'
                                            onChange={formik.handleChange}
                                            value={formik.values.password}
                                        />
                                        {formik.touched.password && formik.errors.password && (
                                            <Error errorText={formik.errors.password} />
                                        )}
                                    </div>
                                </div>

                                {showTwoFactor && (
                                    <div className='mt-6'>
                                        <Input
                                            label={t('auth.twoFactorToken')}
                                            placeholder={t('auth.enter_twoFactorToken')}
                                            {...formik.getFieldProps('twoFactorToken')}
                                        />
                                    </div>
                                )}

                                <Button
                                    label={t('auth.login')}
                                    className='mt-8'
                                    onClick={() => formik.handleSubmit()}
                                    loading={loginWithPassword.isPending}
                                />
                            </div>
                        </div>
                    </div>
                </div>

                <div className='flex-1 min-w-[50%] lg:flex hidden justify-center items-center'>
                    <img src={LogoImage} className='h-14' />
                </div>
            </div>
        </div>
    )
}

export default Login