'use client'

import React, {
  useState,
  type FormEvent,
  type ChangeEvent,
  useEffect,
  useTransition
} from 'react'
import { useAuthStore } from '@/zustand/authStore'
import { redirect, useRouter } from 'next/navigation'
import StepEnterNumber from '@/features/auth/components/StepEnterNumber'
import { AUTH_PAGE_ELEMENT } from '@/enums'
import AuthFormWrapper from '@/features/auth/components/AuthFormWrapper'
import { useCheckUserExistsLazy } from '@/hooks/auth/useCheckUserExists'
import { useAuthTempStore } from '@/zustand/authTempStroe'

type Props = object

function AuthIndex ({}: Props) {
  const update_temp_store = useAuthTempStore(state => state.update)
  const user_temp_store = useAuthTempStore(state => state.user)
  const [number, setNumber] = useState(user_temp_store?.number ?? '')
  const [isPending, startTransition] = useTransition()
  const isAuthenticated = useAuthStore(state => state.isAuthenticated)
  const { run: runUserExistCheck } = useCheckUserExistsLazy()
  const router = useRouter()

  useEffect(() => {
    if (isAuthenticated) {
      redirect('/')
    }
  }, [isAuthenticated])

  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.name == AUTH_PAGE_ELEMENT.INPUT_PHONE) {
      setNumber(() => e.target.value)
    }
  }

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    startTransition(async () => {
      try {
        /* DEV SECTION */
        /* REMOVE THIS CODE FOR PRODUCTION */
        throw false
        /* EMD OF DEV SECTION */

        /* SECTION DETAILS */
        /* If user is already registered, go to login page */
        /* Otherwise go to signup page */
        /* We store auth data in a temp auth store so the next page must */
        /*  access the phone number entered in this page */
        /*  and if it doesnt, it will ask for the number again */
        const userExists = await runUserExistCheck(number)
        update_temp_store({
          number: number,
          mustLogin: userExists
        })
        if (userExists) {
          router.push('auth/login')
        } else {
          router.push('auth/signup')
        }
      } catch (ex) {
        console.error(ex)
        // TODO: Add toast errors

        /* DEV SECTION */
        /* REMOVE THIS CODE FOR PRODUCTION */
        update_temp_store({
          number: number,
          mustLogin: !number.endsWith('0')
        })
        if (number.endsWith('0')) {
          router.push('auth/signup')
        } else {
          router.push('auth/login')
        }
        /* END OF DEV SECTION */
      }
    })
  }

  return (
    <AuthFormWrapper isPending={isPending} onSubmit={onSubmit}>
      <StepEnterNumber pending={isPending} onChange={onChange} value={number} />
    </AuthFormWrapper>
  )
}

export default AuthIndex
