import { useSiteContext } from '@context/SiteContext'
import useLanguage from '@hooks/useLanguage'
import { useNavigate } from '@solidjs/router'
import { Field, useFormHandler } from 'solid-form-handler'
import { yupSchema } from 'solid-form-handler/yup'
import { Show, onMount } from 'solid-js'
import * as yup from 'yup'
import './login.scss'

import Logo from '@assets/logo.svg'
import useAuth from '@hooks/useAuth'
import useToast from '@hooks/useToast'

const loginSchema = yup.object({
  username: yup.string().required('Username is required'),
  password: yup.string().required('Password is required'),
})

const language = useLanguage()

export default function Login() {
  const { store, setAuth } = useSiteContext()
  const navigate = useNavigate()
  const { clickLogIn } = useAuth(setAuth)
  const notify = useToast()
  const formHandler = useFormHandler(yupSchema(loginSchema))
  const { formData } = formHandler

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

  const submit = async (event) => {
    event.preventDefault()
    await formHandler.validateForm()
    try {
      const { username, password } = formData()
      await clickLogIn(username, password, formHandler.resetForm)
      notify.success({
        title: 'Login success!',
        description: 'Welcome back!',
        closable: true,
      })
    } catch (error) {
      notify.error({
        title: 'Login fail!',
        description: error?.data
          ? language.message[error.data]
          : 'Your username or password input is wrong!',
        closable: 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" onSubmit={submit}>
            <Field
              mode="input"
              name="username"
              formHandler={formHandler}
              render={(field) => (
                <label class="form-control w-full pb-5">
                  <label
                    class="input input-bordered flex items-center gap-2 w-full"
                    classList={{ 'input-error': field.helpers.error }}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 16 16"
                      fill="currentColor"
                      class="w-4 h-4 opacity-70"
                    >
                      <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z" />
                    </svg>
                    <input
                      id="username"
                      type="text"
                      class="grow w-full"
                      placeholder="Username"
                      {...field.props}
                    />
                  </label>

                  <Show when={field.helpers.error}>
                    <div class="label">
                      <span class="label-text-alt text-red-600">
                        {field.helpers.errorMessage}
                      </span>
                    </div>
                  </Show>
                </label>
              )}
            />
            <Field
              mode="input"
              name="password"
              formHandler={formHandler}
              render={(field) => (
                <label class="form-control w-full">
                  <label
                    class="input input-bordered flex items-center gap-2 w-full"
                    classList={{ 'input-error': field.helpers.error }}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 16 16"
                      fill="currentColor"
                      class="w-4 h-4 opacity-70"
                    >
                      <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z" />
                    </svg>
                    <input
                      id="password"
                      type="password"
                      class="grow w-full"
                      placeholder="Password"
                      {...field.props}
                    />
                  </label>

                  <Show when={field.helpers.error}>
                    <div class="label">
                      <span class="label-text-alt text-red-600">
                        {field.helpers.errorMessage}
                      </span>
                    </div>
                  </Show>
                </label>
              )}
            />
            <div class="card-actions justify-end mt-5">
              <button type="submit" class="btn btn-primary">
                {language.ui.login}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
