'use client'

import {FormEventHandler, FunctionComponent, useState} from 'react'
import PageTitle from '@/components/custom/pageTitle'
import {Button} from '@/components/ui/button'
import {cn} from '@/lib/utils'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import Actions from '@actions'
import useServerAction from '@hooks/useServerAction'

const LoginForm: FunctionComponent = () => {
  const [email, setEmail] = useState<string>('')
  const [password, setPassword] = useState<string>('')
  const [username, setUsername] = useState<string>('')
  const [passwordConfirmation, setPasswordConfirmation] = useState<string>('')
  const [isSignUp, setIsSignUp] = useState<boolean>(false)
  const [isPending, signInOrRegister] = useServerAction(Actions.signInOrRegister)

  const validEmail = !!email.match(/\w+@\w+\.\w+/)
  const validUsername = username.length >= 3
  const validPassword = password.length >= 6

  const submitHandler: FormEventHandler<HTMLFormElement> = evt => {
    evt.preventDefault()
    // De void operator zorgt er voor dat ESLint geen foutmelding geeft over het gebruik van promises waarvoor geen
    // await, of then en catch gebruikt wordt.
    void signInOrRegister({email, password, username: isSignUp ? username : undefined})
  }

  return (
    <div className="flex flex-col justify-center">
      <div className="mb-4">
        <PageTitle>My contacts</PageTitle>
        <p>Log in to your existing account or create a new one with a real or fake email-address.</p>
      </div>

      <div className="flex flex-row justify-between mb-4">
        <Button variant="link" className={cn('p-0 text-xl', {underline: !isSignUp})} onClick={() => setIsSignUp(false)}>
          Sign in
        </Button>
        <Button variant="link" className={cn('p-0 text-xl', {underline: isSignUp})} onClick={() => setIsSignUp(true)}>
          Sign up
        </Button>
      </div>

      <div className="mt-4">
        <form onSubmit={submitHandler}>
          <div>
            <Label htmlFor="email">Email address</Label>
            <Input
              type="email"
              id="email"
              placeholder="Email"
              value={email}
              required
              onChange={e => setEmail(e.target.value)}
            />
            <p className="text-red-600">
              {!validEmail && email !== '' ? 'Please enter a valid email address' : <span>&nbsp;</span>}
            </p>
          </div>

          {isSignUp && (
            <div>
              <Label htmlFor="username">Username</Label>
              <Input
                type="text"
                id="username"
                required
                placeholder="Username"
                className={cn({'border-red-600': !validUsername && username !== ''})}
                value={username}
                onChange={e => setUsername(e.target.value)}
              />
              <p className="text-red-600">
                {!validEmail && email !== '' ? (
                  'Your username must me at least 3 characters long.'
                ) : (
                  <span>&nbsp;</span>
                )}
              </p>
            </div>
          )}

          <div>
            <Label htmlFor="password">Password</Label>
            <Input
              type="password"
              id="password"
              placeholder="Password"
              className={cn({'border-red-600': !validPassword && password !== ''})}
              value={password}
              required
              onChange={e => setPassword(e.target.value)}
            />
            <p className="text-red-600">
              {!validPassword && password !== '' ? (
                'Your password must be at least 6 characters long.'
              ) : (
                <span>&nbsp;</span>
              )}
            </p>
          </div>

          {isSignUp && (
            <div>
              <Label htmlFor="passwordConfirmation">Confirm your password</Label>
              <Input
                type="password"
                id="passwordConfirmation"
                placeholder="Confirm you password"
                className={cn({
                  'border-red-600': !validPassword && passwordConfirmation !== '' && passwordConfirmation !== password,
                })}
                value={passwordConfirmation}
                required
                onChange={e => setPasswordConfirmation(e.target.value)}
              />
              <p className="text-red-600">
                {!validPassword && passwordConfirmation !== '' && passwordConfirmation !== password ? (
                  'You must enter the same password as you did above.'
                ) : (
                  <span>&nbsp;</span>
                )}
              </p>
            </div>
          )}

          <SubmitButtonWithLoading
            loading={isPending}
            loadingText={isSignUp ? 'Creating your account...' : 'Logging in ...'}
            text={isSignUp ? 'Sign up' : 'Log in'}
          />
        </form>
      </div>
    </div>
  )
}

export default LoginForm
