'use client'

import Button from '@/components/button/PrimaryButton'
import InputField from '@/components/input/InputField'
import { AUTH_PAGE_ELEMENT, AUTH_STEP } from '@/enums'
import { LoginOTPRequestType } from '@/app/auth/login/types/Types'
import Image from 'next/image'
import React, { useState } from 'react'
import type { ChangeEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useOtpRequest } from '@/app/auth/login/hooks/useAuthData'
import { useParams } from 'next/navigation'
import { toast } from '@/components/Toast'
import StepOtp from './StepOtp'
import { extractErrorMessage } from '@/lib/func'

type StepEnterNumberProps = {
  pending?: boolean
  onChange?: (event: ChangeEvent<HTMLInputElement>) => void
  value?: string
}

function StepEnterNumber(_props: StepEnterNumberProps = {}) {
  void _props

  const { t } = useTranslation('auth')
  const { name } = useParams()
  const [step, setStep] = useState(AUTH_STEP.ENTER_NUMBER)
  const { mutate: mutateOtpRequest, isPending } = useOtpRequest()


  const formik = useFormik<LoginOTPRequestType>({
    initialValues: {
      phone: '',
      slug: '',
    },
    validationSchema: Yup.object({
      phone: Yup.string().required('Errors.PhoneNumberRequired').matches(/^09\d{9}$/, 'Errors.PhoneNumberFormat'),
    }),
    onSubmit: (values) => {
      if (name) {
        values.slug = name as string
        mutateOtpRequest(values, {
          onSuccess: () => {
            toast(t('otp_sent'), 'success')
            setStep(AUTH_STEP.ENTER_OTP)
          },
          onError: (error) => {
            toast(extractErrorMessage(error), 'error')

          }
        })
      }
    }
  })


  return (
    <>
      <Image
        className='object-cover w-full h-full max-h-1/2 lg:max-h-full lg:w-1/2'
        src={'/assets/images/login-banner.png'}
        alt='login banner'
        width={100}
        height={100}
        unoptimized
        priority
      />
      <div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
        <div className='w-full'>
          <div className='pt-4'>
            {
              step === AUTH_STEP.ENTER_NUMBER && (
                <>
                  <h6 className='text-lg font-bold'>{t('Enter.Heading')}</h6>
                  <p className='mt-3 text-[13px]'>{t('Enter.Description')}</p>
                </>
              )
            }
            {
              step === AUTH_STEP.ENTER_OTP && (
                <>
                  <h6 className='text-lg font-bold'>{t('OTP.Heading')}</h6>
                  <p className='mt-3 text-[13px]'>{t('OTP.Description', { phoneNumber: formik.values.phone })}</p>
                </>
              )
            }
          </div>
          {step === AUTH_STEP.ENTER_NUMBER && (
            <InputField
              inputMode='tel'
              autoComplete='tel'
              className='mt-10 w-full bg-container'
              htmlFor={AUTH_PAGE_ELEMENT.INPUT_PHONE}
              labelText={t('Enter.LabelPhoneNumber')}
              {...formik.getFieldProps('phone')}
              placeholder='09120000000'
            />
          )}
          {step === AUTH_STEP.ENTER_OTP && (
            <StepOtp phone={formik.values.phone} slug={formik.values.slug} />
          )}
        </div>
        {
          step === AUTH_STEP.ENTER_NUMBER && (
            <Button
              disabled={!formik.isValid}
              pending={isPending}
              type='button'
              onClick={() => formik.handleSubmit()}
              className='dark:bg-white dark:text-black hover:dark:bg-white'
            >
              {t('Enter.ButtonSubmit')}
            </Button>
          )
        }
      </div>
    </>
  )
}

export default StepEnterNumber
