"use client";
import React, { useState, type ReactElement } from 'react'
import Button from '@/Components/Buttons/Button'
import Input from '@/Components/Inputs/Input'
import RequestPasswordReset from '@/Components/Auth/RequestPasswordReset'
import { useLocalStorage } from '@uidotdev/usehooks'
import AuthApi from '@/Components/Auth/AuthApi'

export interface ISignInProps {
  onSuccess?: () => void
  onFailure?: () => void
}

export default function SignIn({
  onSuccess,
  onFailure
}: ISignInProps): ReactElement {
  const [loading, setLoading] = useState(false)
  const [, setAccessToken] = useLocalStorage('access_token', null)
  const [, setUser] = useLocalStorage('user', null)
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showReset, setShowReset] = useState(false)

  const handleSignIn = async (e?: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement, MouseEvent> | React.FormEvent<HTMLFormElement>): Promise<void> => {
    e?.preventDefault()
    if (loading) return
    try {
      setLoading(true)
      const response = await AuthApi.signIn(email, 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 (
    <div>
      {showReset && <RequestPasswordReset />}
      {
        !showReset &&
        <form className='flex flex-col gap-4 max-w-lg' onSubmit={async e => { await handleSignIn(e) }}>
          <div>
            <div className='text-xl font-semibold'>Sign In</div>
            <div className='text-slate-500 font-light'>Sign into your account.</div>
          </div>
          <Input
            id='email'
            testId='email'
            value={email}
            onChange={value => { setEmail(value ?? '') }}
            cleaner={(value?: string) => (value ?? '').trim().toLowerCase()}
            placeholder='Email'
          />
          <div>
            <Input
              id='password'
              testId='password'
              value={password}
              onChange={value => { setPassword(value ?? '') }}
              placeholder='Password'
              type='password'
            />
            <div className='w-full text-right'>
              <span
                onClick={() => { setShowReset(true) }}
                className='transition hover:cursor-pointer hover:underline text-slate-400 hover:text-slate-800 text-sm'>
                Forgot your password?
              </span>
            </div>
          </div>
          <Button onClick={handleSignIn}>Sign In</Button>
        </form>
      }
    </div>
  )
}
