/* eslint-disable no-duplicate-imports */
import { sendLinkForgot } from '@/api/Auth'
import { login } from '@/rtk/dispatches/auth'
import { useAppDispatch } from '@/rtk/hooks'
import type { PaperProps } from '@mantine/core'
import {
  Anchor,
  Button,
  Divider,
  Group,
  Image,
  Paper,
  PasswordInput,
  Stack,
  TextInput,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { upperFirst, useToggle } from '@mantine/hooks'
import { notifications } from '@mantine/notifications'
import axios from 'axios'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import classes from './Authentication.module.css'
interface AuthenticationFormProps extends PaperProps {
  type?: string
}

export const AuthenticationForm = (props: AuthenticationFormProps) => {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const [type, toggle] = useToggle(['login', 'forgot'])
  const [emailReset, setEmailReset] = useState('')
  const [check, setCheck] = useState(false)
  const form = useForm({
    initialValues: {
      email: '',
      name: '',
      password: '',
      terms: true,
    },

    validate: {
      email: (val: string) => (/^\S+@\S+$/.test(val) ? null : 'Invalid email'),
      password: (val: string) =>
        val.length < 8 ? 'Password should include at least 8 characters' : null,
    },
  })

  const handleLogin = async (formData: { email: string; password: string }) => {
    if (check === false) {
      setCheck(true)
      dispatch(login(formData, notifications, navigate)).then(() => {
        setCheck(false)
      })
    }
  }

  const handleForgot = async () => {
    try {
      setCheck(true)
      const res = await axios.get(sendLinkForgot + '?email=' + emailReset)

      if (res.data.status) {
        notifications.show({
          title: 'Success',
          message: 'Send mail success. Please check!',
          color: 'green',
        })

        setCheck(false)
      } else {
        notifications.show({
          title: 'Error',
          message: res.data.mess,
          color: 'red',
        })
        setCheck(false)
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <Paper
      className={classes.loginForm}
      radius="md"
      p="xl"
      withBorder
      {...props}
      w={'400px'}
      m={'auto'}
    >
      <Image src="/logo.jpg" w={'50%'} m={'auto'}></Image>
      <Divider
        label={type === 'login' ? 'Login' : 'Forgot password'}
        labelPosition="center"
        my="lg"
      />

      {type === 'login' ? (
        <form
          onSubmit={form.onSubmit(
            (values: { email: string; password: string }) => {
              const formData = {
                email: values.email,
                password: values.password,
              }
              handleLogin(formData)
            },
          )}
        >
          <Stack>
            <TextInput
              required
              label="Email"
              type="email"
              placeholder="hello@mantine.dev"
              value={form.values.email}
              onChange={(event: { currentTarget: { value: string } }) =>
                form.setFieldValue('email', event.currentTarget.value)
              }
              error={form.errors.email && 'Invalid email'}
              radius="md"
            />
            <PasswordInput
              required
              label="Password"
              placeholder="Your password"
              value={form.values.password}
              onChange={(event: { currentTarget: { value: string } }) =>
                form.setFieldValue('password', event.currentTarget.value)
              }
              error={
                form.errors.password &&
                'Password should include at least 8 characters'
              }
              radius="md"
            />
          </Stack>

          <Group justify="space-between" mt="xl">
            <Anchor
              component="button"
              type="button"
              c="dimmed"
              onClick={() => toggle()}
              size="xs"
            >
              {'Forgotten password?'}
            </Anchor>
            <Button type="submit" radius="xl">
              {upperFirst(type)}
            </Button>
          </Group>
        </form>
      ) : (
        <>
          <TextInput
            required
            label="Email"
            type="email"
            placeholder="hello@mantine.dev"
            value={emailReset}
            onChange={(e) => setEmailReset(e.target.value)}
            error={
              emailReset !== '' &&
              !/^\S+@\S+$/.test(emailReset) &&
              'Invalid email'
            }
            radius="md"
          />
          <Group justify="space-between" mt="xl">
            <Anchor
              component="button"
              type="button"
              c="dimmed"
              onClick={() => toggle()}
              size="xs"
            >
              {'Log in'}
            </Anchor>
            <Button
              loading={check}
              type="submit"
              radius="xl"
              disabled={!/^\S+@\S+$/.test(emailReset) ? true : false}
              onClick={() => handleForgot()}
            >
              Send
            </Button>
          </Group>
        </>
      )}
    </Paper>
  )
}

export default AuthenticationForm
