import { useSiteContext } from '@context/SiteContext'
import { createForm } from '@felte/solid'
import { validator } from '@felte/validator-yup'
import useLanguage from '@hooks/useLanguage'
import { useNavigate } from '@solidjs/router'
import { IconKey, IconUser } from '@tabler/icons-solidjs'
import { onMount } from 'solid-js'
import * as yup from 'yup'
import './login.scss'

import Logo from '@assets/images/logo.svg'
import TextInput from '@components/common/TextInput'
import useAuth from '@hooks/useAuth'
import useToast from '@hooks/useToast'

const loginSchema = (language, isRequired) =>
  yup.object({
    username: yup.string().required(isRequired(language.ui.username)),
    password: yup.string().required(isRequired(language.ui.password)),
  })

export default function Login() {
  const { store, setAuth } = useSiteContext()
  const { language, isRequired } = useLanguage()
  const navigate = useNavigate()
  const { clickLogIn } = useAuth(setAuth)
  const notify = useToast()

  const { form, errors } = createForm({
    extend: [validator({ schema: loginSchema(language, isRequired) })],
    onSubmit: async (values) => {
      try {
        const { username, password } = values
        return await clickLogIn(username, password)
      } catch (error) {
        notify.error({
          title: 'Login fail!',
          description: error?.data
            ? language.message[error.data]
            : 'Your username or password input is wrong!',
          closable: true,
        })
      }
    },
  })

  onMount(() => {
    if (store.auth) {
      navigate('/', { replace: true })
    }
  })

  return (
    <div class="login-page">
      <div class="card glass card-compact login-wrap shadow-xl">
        <div class="h-44">
          <picture class="logo">
            <source srcSet={Logo} type="image/png" media="(min-width: 600px)" />
            <img src={Logo} alt="logo" />
          </picture>
        </div>
        <div class="card-body">
          <h1 class="card-title">{language.ui.login}</h1>
          <form autoComplete="off" use:form>
            <TextInput
              name="username"
              placeholder={language.ui.username}
              icon={IconUser}
              label={language.ui.username}
              error={errors('username')}
            />
            <TextInput
              name="password"
              type="password"
              placeholder={language.ui.password}
              icon={IconKey}
              label={language.ui.password}
              error={errors('password')}
            />
            <div class="card-actions justify-end mt-2">
              <button type="submit" class="btn btn-primary">
                {language.ui.login}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
