"use client";
import React, { useState, type ReactElement } from 'react'
import { useForm } from 'react-hook-form'
import Button from '@/Components/Buttons/Button'
import Input from '@/Components/Inputs/Input'
import InputError from '@/Components/Errors/InputError/InputError'
import { useLocalStorage } from '@uidotdev/usehooks'
import AuthApi from '@/Components/Auth/AuthApi'
import Utilities from './Utilities'

interface ISignUpForm {
  firstName: string
  lastName: string
  email: string
  password: string
  confirmPassword: string
}
export interface ISignUpProps {
  firstName?: string
  lastName?: string
  email?: string
  password?: string
  confirmPassword?: string
  onSuccess?: () => void
  onFailure?: () => void
}

export default function SignUp({
  firstName,
  lastName,
  email,
  password,
  confirmPassword,
  onSuccess,
  onFailure
}: ISignUpProps): ReactElement {
  const [loading, setLoading] = useState(false)
  const [, setAccessToken] = useLocalStorage('access_token', null)
  const [, setUser] = useLocalStorage('user', null)
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm<ISignUpForm>({
    defaultValues: {
      firstName,
      lastName,
      email,
      password,
      confirmPassword
    }
  })

  const onSubmit = async (data: ISignUpForm): Promise<void> => {
    if (loading) return
    try {
      setLoading(true)
      const response = await AuthApi.signUp(data.firstName, data.lastName, data.email, data.password)
      setLoading(false)
      console.log(response)
      setAccessToken(response.data.access_token)
      setUser(response.data.user)
      onSuccess?.()
    } catch (error) {
      console.error(error)
      setLoading(false)
      onFailure?.()
    }
  }

  return (
    <form className='flex flex-col gap-4 max-w-lg' onSubmit={handleSubmit(onSubmit)}>
      <div>
        <div className='text-xl font-semibold'>Sign Up</div>
        <div className='text-slate-500 font-light'>Create a new account.</div>
      </div>
      <div>
        <Input
          id='firstName'
          testId='firstName'
          placeholder='First Name'
          autofocus={true}
          validator={register('firstName', { required: true })}
        />
        <InputError fieldError={errors.firstName} />
      </div>
      <div>
        <Input
          id='lastName'
          testId='lastName'
          cleaner={(value?: string) => (value ?? '').trim()}
          placeholder='Last Name'
          validator={register('lastName', { required: true })}
        />
        <InputError fieldError={errors.lastName} />
      </div>
      <div>
        <Input
          id='email'
          testId='email'
          cleaner={(value?: string) => (value ?? '').trim().toLowerCase()}
          placeholder='Email'
          validator={register('email', { required: true, pattern: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*(\+[a-z0-9-]+)?@[a-z0-9-]+(\.[a-z0-9-]+)*$/i })}
        />
        <InputError fieldError={errors.email} errorMessages={{ pattern: 'Email is invalid.' }} />
      </div>
      <div>
        <Input
          id='password'
          testId='password'
          placeholder='Password'
          validator={register('password', Utilities.PasswordConstraints)}
          type='password'
        />
        <InputError
          fieldError={errors.password}
          errorMessages={Utilities.PasswordErrorMessages}
        />
      </div>
      <div>
        <Input
          id='confirmPassword'
          testId='confirmPassword'
          placeholder='Confirm Password'
          validator={register('confirmPassword', {
            required: true,
            validate: {
              passwordsMatch: (value: string) => value === watch('password')
            }
          })}
          type='password'
        />
        <InputError
          fieldError={errors.confirmPassword}
          errorMessages={{
            passwordsMatch: 'Passwords do not match.'
          }}
        />
      </div>
      <Button onClick={handleSubmit(onSubmit)} disabled={loading}>Sign Up</Button>
    </form>
  )
}
