import Logo from '@assets/images/logo.svg'
import { errorTip, labelWithIcon } from '@components/Common'
import { useAuth, useSignInUp } from '@hooks/useAuth'
import {
  Box,
  Button,
  Card,
  Center,
  Container,
  Group,
  Image,
  PasswordInput,
  TextInput,
  Title,
} from '@mantine/core'
import { isNotEmpty, useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import {
  IconCircleCheck,
  IconCircleXFilled,
  IconKeyFilled,
  IconUserFilled,
} from '@tabler/icons-react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { s_logo, s_wrapper } from './Login.module.scss'

export default function Login() {
  const {
    auth: { isLogged },
    setAuth,
  } = useAuth()
  const { t } = useTranslation()
  const navigate = useNavigate()
  const { onLogin } = useSignInUp(setAuth)
  const form = useForm({
    initialValues: {
      username: '',
      password: '',
    },
    validate: {
      username: isNotEmpty(
        t('message_is_required', { field: t('ui_username') }),
      ),
      password: isNotEmpty(
        t('message_is_required', { field: t('ui_password') }),
      ),
    },
    enhanceGetInputProps: (payload) => ({
      error: errorTip(payload.inputProps.error),
    }),
  })

  useEffect(() => {
    if (isLogged) {
      navigate('/', { replace: true })
    }
  })

  const onSubmitLogin = async (values) => {
    try {
      await onLogin(values)
      notifications.show({
        color: 'green.5',
        icon: <IconCircleCheck />,
        title: t('message_login_success'),
        message: t('message_welcom_back'),
      })
    } catch (error) {
      notifications.show({
        color: 'red.5',
        icon: <IconCircleXFilled />,
        title: t('message_login_fail'),
        message: error?.data ? t(error.data) : t('message_login_wrong'),
      })
    }
  }

  return (
    <Container
      fluid
      style={{
        background: '#fff url(/images/bg-login.jpg) no-repeat fixed center',
        backgroundSize: 'cover',
      }}
      h="100svh"
    >
      <Center h="100svh">
        <Card
          shadow="xl"
          radius={20}
          w="40%"
          maw={500}
          miw={320}
          className={s_wrapper}
        >
          <Card.Section>
            <Image src={Logo} className={s_logo} alt="logo" />
          </Card.Section>
          <form onSubmit={form.onSubmit(onSubmitLogin)}>
            <Box pos="relative" style={{ zIndex: 4 }}>
              <Title order={1} fz={18} mb="sm" mt="sm">
                {t('ui_login')}
              </Title>
              <TextInput
                withAsterisk
                label={labelWithIcon(t('ui_username'), IconUserFilled)}
                placeholder={t('ui_username')}
                key={form.key('username')}
                {...form.getInputProps('username')}
              />
              <PasswordInput
                withAsterisk
                label={labelWithIcon(t('ui_password'), IconKeyFilled)}
                placeholder={t('ui_password')}
                mt="sm"
                key={form.key('password')}
                {...form.getInputProps('password')}
              />
              <Group justify="flex-end" mt="md">
                <Button type="submit">{t('ui_login')}</Button>
              </Group>
            </Box>
          </form>
        </Card>
      </Center>
    </Container>
  )
}
