import { useGoogleLogin } from '@react-oauth/google'
import { emailRegex } from '@/utils/formRegexs'

import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch, RootState } from '@/rtk/store'
import {
  loginAsync,
  loginERPAsync,
  loginWithGoogleAsync,
} from '@/rtk/slices/authSlice'

import { Box, Button, PasswordInput, TextInput } from '@mantine/core'
import { useForm } from '@mantine/form'

import classes from './AuthenticationImage.module.css'
import { useNavigate } from 'react-router-dom'

import ImgERP from '../../lib/images/erp.jpg'
import { useState } from 'react'

type TLogin = {
  email: string
  password: string
}

const Login = () => {
  const navigate = useNavigate()
  const dispatch = useDispatch<AppDispatch>()
  const { status } = useSelector((state: RootState) => state.auth)
  const [isLoginERP, setIsLoginERP] = useState(false)

  const formLogin = useForm<TLogin>({
    initialValues: {
      email: '',
      password: '',
    },
    validate: (values) => ({
      email:
        values.email === ''
          ? 'Email is required'
          : isLoginERP
          ? null
          : emailRegex.test(values.email)
          ? null
          : 'Invalid email',

      password: values.password === '' ? 'Password is required' : null,
    }),
  })

  const handleLogin = async (values: TLogin) => {
    if (isLoginERP) {
      const payload = {
        userEmail: values.email,
        password: values.password,
      }
      const resultAction = await dispatch(loginERPAsync(payload))

      if (loginERPAsync.fulfilled.match(resultAction)) {
        // set interval to wait for localStorage to be set
        window.location.href = '/dashboard'
      }
    } else {
      const resultAction = await dispatch(loginAsync(values))

      if (loginAsync.fulfilled.match(resultAction)) {
        navigate('/dashboard')
      }
    }
  }

  const handleLoginGG = useGoogleLogin({
    onSuccess: async (codeResponse) => {
      const accessToken = codeResponse.access_token
      const resultAction = await dispatch(loginWithGoogleAsync(accessToken))

      if (loginWithGoogleAsync.fulfilled.match(resultAction)) {
        navigate('/dashboard')
      }
    },
    onError: (error) => console.log('Login Failed:', error),
  })

  return (
    <form
      style={{
        padding: '10px 20px',
      }}
      onSubmit={formLogin.onSubmit(handleLogin)}
    >
      <div style={{ textAlign: 'center' }}>
        <h3 className={classes.title}>
          {isLoginERP ? 'Login with ERP account' : 'Login with ATC account'}
        </h3>
      </div>
      <TextInput
        label={isLoginERP ? 'Username/email:' : 'Email address'}
        placeholder="hello@gmail.com"
        value={formLogin.values.email}
        error={formLogin.errors.email}
        onChange={(e) => {
          formLogin.setFieldValue('email', e.target.value!)
        }}
        required
        size="md"
      />
      <PasswordInput
        label="Password"
        placeholder="Your password"
        value={formLogin.values.password}
        error={formLogin.errors.password}
        onChange={(e) => {
          formLogin.setFieldValue('password', e.target.value!)
        }}
        required
        mt="md"
        size="md"
      />

      <Button
        fullWidth
        mt="xl"
        size="md"
        type="submit"
        loading={status === 'loading'}
      >
        Sign in
      </Button>

      {!isLoginERP ? (
        <Box ta={'center'}>
          <Button
            variant="outline"
            color="#228be6"
            radius={'5px'}
            className={classes['google-btn']}
            onClick={() => setIsLoginERP(true)}
          >
            <img
              src={ImgERP}
              alt="ERP logo"
              className={classes['google-icon']}
            />
            Sign in with ERP
          </Button>
        </Box>
      ) : (
        <Box ta={'center'}>
          <Button
            variant="outline"
            color="#228be6"
            radius={'5px'}
            className={classes['google-btn']}
            onClick={() => setIsLoginERP(false)}
          >
            Sign in normally
          </Button>
        </Box>
      )}

      <Box ta={'center'}>
        <Button
          variant="outline"
          color="#228be6"
          radius={'5px'}
          onClick={() => handleLoginGG()}
          className={classes['google-btn']}
        >
          <img
            src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/480px-Google_%22G%22_logo.svg.png"
            alt="Google logo"
            className={classes['google-icon']}
          />
          Sign in with Google
        </Button>
      </Box>
    </form>
  )
}

export default Login
