// // ** React Imports
// import { ChangeEvent, useState, KeyboardEvent } from 'react'

// // ** Next Import
// import Link from 'next/link'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** KYC Form Component
// import KycForm from './KycForm'

// export type ErrCallbackType = (err: { [key: string]: string }) => void

// interface ValuesObject {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(2),
//   color: theme.palette.primary.main
// }))

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   }
// }))

// const defaultValues: { [key: string]: string } = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// const VerifyUser = ({ mobile, token, otp }: { mobile: string; token: string; otp: number }) => {
//   // ** State
//   const [isBackspace, setIsBackspace] = useState<boolean>(false)
//   const [showKyc, setShowKyc] = useState<boolean>(false)

//   // ** Hooks
//   const theme = useTheme()
//   const {
//     control,
//     handleSubmit,
//     formState: { errors }
//   } = useForm<ValuesObject>({ defaultValues })

//   // ** Vars
//   const errorsArray = Object.keys(errors)

//   const handleChange = (event: ChangeEvent, onChange: (...event: any[]) => void) => {
//     if (!isBackspace) {
//       onChange(event)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (form[index].value && form[index].value.length) {
//         form.elements[index + 1].focus()
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: KeyboardEvent) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (index >= 1) {
//         if (!(form[index].value && form[index].value.length)) {
//           form.elements[index - 1].focus()
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     return (Object.keys(defaultValues) as (keyof ValuesObject)[]).map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <Box
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             component={CleaveInput}
//             onKeyDown={handleKeyDown}
//             onChange={(event: ChangeEvent) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ [theme.breakpoints.down('sm')]: { px: `${theme.spacing(2)} !important` } }}
//           />
//         )}
//       />
//     ))
//   }

//   const onSubmit = (data: ValuesObject) => {
//     const enteredOtp = Object.values(data).join('')
//     console.log('Entered OTP:', enteredOtp)
//     console.log('Expected OTP:', otp)
    
//     // You can add OTP validation here if needed
//     // For now, just show KYC form
//     setShowKyc(true)
//   }

//   // If showKyc is true, render the KYC form
//   if (showKyc) {
//     return <KycForm />
//   }

//   return (
//     <Box sx={{ width: '100%', maxWidth: 400 }}>
//       <svg width={34} height={23.375} viewBox='0 0 32 22' fill='none' xmlns='http://www.w3.org/2000/svg'>
//         <path
//           fillRule='evenodd'
//           clipRule='evenodd'
//           fill={theme.palette.primary.main}
//           d='M0.00172773 0V6.85398C0.00172773 6.85398 -0.133178 9.01207 1.98092 10.8388L13.6912 21.9964L19.7809 21.9181L18.8042 9.88248L16.4951 7.17289L9.23799 0H0.00172773Z'
//         />
//         <path
//           fill='#161616'
//           opacity={0.06}
//           fillRule='evenodd'
//           clipRule='evenodd'
//           d='M7.69824 16.4364L12.5199 3.23696L16.5541 7.25596L7.69824 16.4364Z'
//         />
//         <path
//           fill='#161616'
//           opacity={0.06}
//           fillRule='evenodd'
//           clipRule='evenodd'
//           d='M8.07751 15.9175L13.9419 4.63989L16.5849 7.28475L8.07751 15.9175Z'
//         />
//         <path
//           fillRule='evenodd'
//           clipRule='evenodd'
//           fill={theme.palette.primary.main}
//           d='M7.77295 16.3566L23.6563 0H32V6.88383C32 6.88383 31.8262 9.17836 30.6591 10.4057L19.7824 22H13.6938L7.77295 16.3566Z'
//         />
//       </svg>
//       <Box sx={{ my: 6 }}>
//         <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//           Two-Step Verification 💬
//         </Typography>
//         <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//           We sent a verification code to your mobile. Enter the code from the mobile in the field below.
//         </Typography>
//         <Typography sx={{ fontWeight: 500 }}>{mobile}</Typography>
//       </Box>
//       <Typography sx={{ fontWeight: 500, color: 'text.secondary' }}>Type your 6 digit security code</Typography>
//       <form onSubmit={handleSubmit(onSubmit)}>
//         <CleaveWrapper
//           sx={{
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'space-between',
//             ...(errorsArray.length && {
//               '& .invalid:focus': {
//                 borderColor: theme => `${theme.palette.error.main} !important`,
//                 boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//               }
//             })
//           }}
//         >
//           {renderInputs()}
//         </CleaveWrapper>
//         {errorsArray.length ? (
//           <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid OTP</FormHelperText>
//         ) : null}
//         <Button fullWidth type='submit' variant='contained' sx={{ mt: 2 }}>
//           Verify My Account
//         </Button>
//       </form>
//       <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
//         <LinkStyled href='/' onClick={e => e.preventDefault()}>
//           Resend
//         </LinkStyled>
//       </Box>
//     </Box>
//   )
// }

// export default VerifyUser


// api integareted //////////////////////////////////////////////////////

// ** React Imports
// import { ChangeEvent, useState, KeyboardEvent, useEffect } from 'react'
// import { useRouter } from 'next/router'
// import Icon from 'src/@core/components/icon'
// // ** Next Import
// import Link from 'next/link'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'
// import CircularProgress from '@mui/material/CircularProgress'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'
// import toast from 'react-hot-toast'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'
// import CryptoJS from 'crypto-js'

// export type ErrCallbackType = (err: { [key: string]: string }) => void

// interface ValuesObject {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// interface VerifyUserProps {
//   token: string
//   mobile: string
//   email: string
// }

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(2),
//   color: theme.palette.primary.main
// }))

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   }
// }))

// const defaultValues: { [key: string]: string } = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// // AES Encryption function for OTP
// const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

// const encryptAES = (text: string): string => {
//   try {
//     const key = CryptoJS.SHA256(SECRET_KEY)
//     const iv = CryptoJS.lib.WordArray.random(16)
//     const encrypted = CryptoJS.AES.encrypt(text, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })
//     const combined = iv.clone().concat(encrypted.ciphertext)
//     return CryptoJS.enc.Base64.stringify(combined)
//   } catch (error) {
//     console.error('Encryption error:', error)
//     return text
//   }
// }

// const VerifyUser = ({ token, mobile, email }: VerifyUserProps) => {
//   // ** State
//   const [isBackspace, setIsBackspace] = useState<boolean>(false)
//   const [isVerifying, setIsVerifying] = useState<boolean>(false)
//   const [resendTimer, setResendTimer] = useState<number>(30)
//   const [canResend, setCanResend] = useState<boolean>(false)
  
//   const router = useRouter()
//   // ** Hooks
//   const theme = useTheme()
  
//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors }
//   } = useForm<ValuesObject>({ defaultValues })

//   // Timer for resend functionality
//   useEffect(() => {
//     let timer: NodeJS.Timeout
//     if (resendTimer > 0 && !canResend) {
//       timer = setTimeout(() => setResendTimer(resendTimer - 1), 1000)
//     } else if (resendTimer === 0) {
//       setCanResend(true)
//     }
//     return () => clearTimeout(timer)
//   }, [resendTimer, canResend])

//   // ** Vars
//   const errorsArray = Object.keys(errors)

//   const handleChange = (event: ChangeEvent, onChange: (...event: any[]) => void) => {
//     if (!isBackspace) {
//       onChange(event)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (form[index].value && form[index].value.length) {
//         form.elements[index + 1]?.focus()
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: KeyboardEvent) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (index >= 1) {
//         if (!(form[index].value && form[index].value.length)) {
//           form.elements[index - 1]?.focus()
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     return (Object.keys(defaultValues) as (keyof ValuesObject)[]).map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <Box
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             component={CleaveInput}
//             onKeyDown={handleKeyDown}
//             onChange={(event: ChangeEvent) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ [theme.breakpoints.down('sm')]: { px: `${theme.spacing(2)} !important` } }}
//           />
//         )}
//       />
//     ))
//   }

//   const handleResendCode = async () => {
//     if (canResend && email) {
//       setResendTimer(30)
//       setCanResend(false)
      
//       const toastId = toast.loading('Resending verification code...')
      
//       try {
//         // Call resend OTP API
//         const response = await axios.post(endpoints.auth.resendOTP, {
//           email: email
//         })
        
//         if (response.data.code === 200) {
//           toast.success('Verification code sent successfully!', {
//             id: toastId,
//             duration: 4000
//           })
//         } else {
//           toast.error('Failed to resend code. Please try again.', {
//             id: toastId,
//             duration: 5000
//           })
//         }
//       } catch (error) {
//         console.error('Resend error:', error)
//         toast.error('Failed to resend code. Please try again.', {
//           id: toastId,
//           duration: 5000
//         })
//       }
//     }
//   }

//   const onSubmit = async (data: ValuesObject) => {
//     const otpValue = Object.values(data).join('')
    
//     if (otpValue.length !== 6) {
//       toast.error('Please enter complete 6-digit code')
//       return
//     }
    
//     setIsVerifying(true)
//     const toastId = toast.loading('Verifying OTP...')
    
//     try {
//       // Encrypt the OTP
//       const encryptedOTP = encryptAES(otpValue)
      
//       // Make API call to verify OTP
//       const response = await axios.post(`${endpoints.auth.verifyAccount}/${token}`, {
//         otp: encryptedOTP
//       })
      
//       if (response.data.code === 200) {
//         toast.success('Verification successful! Redirecting...', {
//           id: toastId,
//           duration: 3000
//         })
        
//         // Clear session storage items
//         sessionStorage.removeItem('requiresVerification')
        
//         // Store authentication status
//         localStorage.setItem('isAuthenticated', 'true')
        
//         // Redirect to dashboard or home page
//         setTimeout(() => {
//           router.push('/dashboard')
//         }, 2000)
//       } else {
//         const errorMessage = typeof response.data.content === 'string' 
//           ? response.data.content 
//           : response.data.content?.message || 'Invalid OTP. Please try again.'
        
//         toast.error(errorMessage, {
//           id: toastId,
//           duration: 5000
//         })
        
//         // Clear all OTP inputs
//         reset(defaultValues)
//       }
//     } catch (error: any) {
//       console.error('Verification error:', error)
      
//       let errorMessage = 'Verification failed. Please try again.'
      
//       if (error.response?.data?.content) {
//         if (typeof error.response.data.content === 'string') {
//           errorMessage = error.response.data.content
//         } else if (error.response.data.content.message) {
//           errorMessage = error.response.data.content.message
//         }
//       } else if (error.response?.status === 400) {
//         errorMessage = 'Invalid OTP. Please check and try again.'
//       } else if (!error.response) {
//         errorMessage = 'Network error. Please check your connection.'
//       }
      
//       toast.error(errorMessage, {
//         id: toastId,
//         duration: 5000
//       })
      
//       // Clear all OTP inputs
//       reset(defaultValues)
//     } finally {
//       setIsVerifying(false)
//     }
//   }

//   return (
//     <Box sx={{ width: '100%', maxWidth: 400 }}>
//       <Box sx={{ mb: 4, display: 'flex' }}>
//         <img
//           src='/images/website-logo/LockTrust-logo.png'
//           alt='LockTrust Logo'
//           style={{
//             height: '60px',
//             width: 'auto',
//             objectFit: 'contain'
//           }}
//         />
//       </Box>
//       <Box sx={{ my: 6 }}>
//         <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//           Two-Step Verification 💬
//         </Typography>
//         <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//           We sent a verification code to your mobile. Enter the code from the mobile in the field below.
//         </Typography>
//         <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
//           {email || sessionStorage.getItem('userEmail') || 'your email address'}
//         </Typography>
//         <Typography sx={{ fontWeight: 500 }}>{mobile}</Typography>
//       </Box>
//       <Typography sx={{ fontWeight: 500, color: 'text.secondary' }}>Type your 6 digit security code</Typography>
//       <form onSubmit={handleSubmit(onSubmit)}>
//         <CleaveWrapper
//           sx={{
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'space-between',
//             ...(errorsArray.length && {
//               '& .invalid:focus': {
//                 borderColor: theme => `${theme.palette.error.main} !important`,
//                 boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//               }
//             })
//           }}
//         >
//           {renderInputs()}
//         </CleaveWrapper>
//         {errorsArray.length ? (
//           <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid OTP</FormHelperText>
//         ) : null}
//         <Button 
//           fullWidth 
//           type='submit' 
//           variant='contained' 
//           sx={{ mt: 2 }}
//           disabled={isVerifying}
//         >
//           {isVerifying ? <CircularProgress size={24} color='inherit' /> : 'Verify My Account'}
//         </Button>
//       </form>
//       <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
//         <LinkStyled href='#' onClick={(e) => {
//           e.preventDefault()
//           handleResendCode()
//         }}>
//           {canResend ? 'Resend' : `Resend in ${resendTimer}s`}
//         </LinkStyled>
//       </Box>
//       <Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
//         <Button
//           variant='text'
//           onClick={() => router.push('/login')}
//           sx={{ textTransform: 'none' }}
//           startIcon={<Icon icon='tabler:arrow-left' />}
//         >
//           Back to Login
//         </Button>
//       </Box>
//     </Box>
//   )
// }

// export default VerifyUser



// redirect solve //////////////////////////////////////

// import { ChangeEvent, useState, KeyboardEvent } from 'react'
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'
// import CircularProgress from '@mui/material/CircularProgress'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'
// import toast from 'react-hot-toast'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** Axios
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'
// import CryptoJS from 'crypto-js'
// import authConfig from 'src/configs/auth'

// export type ErrCallbackType = (err: { [key: string]: string }) => void

// interface ValuesObject {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// interface VerifyUserProps {
//   token: string
//   mobile: string
//   email: string
// }

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   }
// }))

// const defaultValues: { [key: string]: string } = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// // AES Encryption function for OTP
// const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

// const encryptAES = (text: string): string => {
//   try {
//     const key = CryptoJS.SHA256(SECRET_KEY)
//     const iv = CryptoJS.lib.WordArray.random(16)
//     const encrypted = CryptoJS.AES.encrypt(text, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })
//     const combined = iv.clone().concat(encrypted.ciphertext)
//     return CryptoJS.enc.Base64.stringify(combined)
//   } catch (error) {
//     console.error('Encryption error:', error)
//     return text
//   }
// }

// const VerifyUser = ({ token, mobile, email }: VerifyUserProps) => {
//   // ** State
//   const [isBackspace, setIsBackspace] = useState<boolean>(false)
//   const [isVerifying, setIsVerifying] = useState<boolean>(false)
  
//   const router = useRouter()
//   // ** Hooks
//   const theme = useTheme()
  
//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors }
//   } = useForm<ValuesObject>({ defaultValues })

//   // ** Vars
//   const errorsArray = Object.keys(errors)

//   const handleChange = (event: ChangeEvent, onChange: (...event: any[]) => void) => {
//     if (!isBackspace) {
//       onChange(event)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (form[index].value && form[index].value.length) {
//         const nextInput = form.elements[index + 1]
//         if (nextInput) nextInput.focus()
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: KeyboardEvent) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)

//       // @ts-ignore
//       const form = event.target.form
//       const index = [...form].indexOf(event.target)
//       if (index >= 1) {
//         if (!(form[index].value && form[index].value.length)) {
//           const prevInput = form.elements[index - 1]
//           if (prevInput) prevInput.focus()
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     return (Object.keys(defaultValues) as (keyof ValuesObject)[]).map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <Box
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             component={CleaveInput}
//             onKeyDown={handleKeyDown}
//             onChange={(event: ChangeEvent) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ [theme.breakpoints.down('sm')]: { px: `${theme.spacing(2)} !important` } }}
//           />
//         )}
//       />
//     ))
//   }

//   const onSubmit = async (data: ValuesObject) => {
//     const otpValue = Object.values(data).join('')
    
//     if (otpValue.length !== 6) {
//       toast.error('Please enter complete 6-digit code')
//       return
//     }
    
//     setIsVerifying(true)
//     const toastId = toast.loading('Verifying OTP...')
    
//     try {
//       // Encrypt the OTP before sending
//       const encryptedOTP = encryptAES(otpValue)
      
//       console.log('=== OTP Verification Request ===')
//       console.log('URL:', `${endpoints.auth.verifyAccount}/${token}`)
//       console.log('Token:', token)
//       console.log('Original OTP:', otpValue)
//       console.log('Encrypted OTP:', encryptedOTP)
      
//       // Make API call to verify OTP with encrypted OTP
//       const response = await axios.post(`${endpoints.auth.verifyAccount}/${token}`, {
//         otp: encryptedOTP
//       })
      
//       console.log('=== OTP Verification Response ===')
//       console.log('Full Response:', response.data)
      
//       // Check for successful response - API returns access token and profile
//       if (response.data && response.data.access) {
//         // Success! Store the tokens
//         const { access, refresh, expiresIn, profile } = response.data
        
//         console.log('Login Successful! User:', profile?.emailId)
//         console.log('User Permissions:', profile?.allPermissions || profile?.permissions)
        
//         // Format permissions for ACL
//         let formattedPermissions = []
//         if (profile?.allPermissions && profile.allPermissions.length > 0) {
//           formattedPermissions = profile.allPermissions
//         } else if (profile?.permissions && profile.permissions.length > 0) {
//           formattedPermissions = profile.permissions.map((p: any) => ({
//             moduleName: p.moduleName,
//             action: p.action
//           }))
//         } else {
//           // Default permissions for merchant dashboard
//           formattedPermissions = [
//             { moduleName: 'dashboard', action: 'CREATE' },
//             { moduleName: 'dashboard', action: 'UPDATE' },
//             { moduleName: 'dashboard', action: 'VIEW' },
//             { moduleName: 'dashboard', action: 'DELETE' }
//           ]
//         }
        
//         // Format user data exactly as AuthContext expects
//         const userData = {
//           id: profile?.uid || profile?.id,
//           role: profile?.isSubUser ? 'subUser' : 'merchant',
//           fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
//           firstName: profile?.firstName,
//           lastName: profile?.lastName,
//           mobileNum: profile?.mobileNum,
//           username: profile?.emailId,
//           email: profile?.emailId,
//           isSubUser: profile?.isSubUser || false,
//           TwoNf: profile?.TwoNf || false,
//           allPermissions: formattedPermissions,
//           permissions: formattedPermissions
//         }
        
//         console.log('Storing User Data:', userData)
        
//         // Store tokens in localStorage with correct keys
//         localStorage.setItem(authConfig.storageTokenKeyName, access)
//         localStorage.setItem('refreshToken', refresh)
//         localStorage.setItem('userData', JSON.stringify(userData))
//         localStorage.setItem('isAuthenticated', 'true')
        
//         // Store in sessionStorage as well
//         sessionStorage.setItem(authConfig.storageTokenKeyName, access)
//         sessionStorage.setItem('userData', JSON.stringify(userData))
//         sessionStorage.setItem('isAuthenticated', 'true')
//         sessionStorage.setItem('userEmail', profile?.emailId || email)
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 2000
//         })
        
//         // Use window.location.href for hard redirect
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//       } 
//       else if (response.data?.code === 200 && response.data?.content?.access) {
//         // Alternative response structure
//         const { access, refresh, profile } = response.data.content
        
//         let formattedPermissions = []
//         if (profile?.allPermissions && profile.allPermissions.length > 0) {
//           formattedPermissions = profile.allPermissions
//         } else if (profile?.permissions && profile.permissions.length > 0) {
//           formattedPermissions = profile.permissions
//         } else {
//           formattedPermissions = [
//             { moduleName: 'dashboard', action: 'CREATE' },
//             { moduleName: 'dashboard', action: 'UPDATE' },
//             { moduleName: 'dashboard', action: 'VIEW' },
//             { moduleName: 'dashboard', action: 'DELETE' }
//           ]
//         }
        
//         const userData = {
//           id: profile?.uid,
//           role: profile?.isSubUser ? 'subUser' : 'merchant',
//           fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
//           firstName: profile?.firstName,
//           lastName: profile?.lastName,
//           mobileNum: profile?.mobileNum,
//           username: profile?.emailId,
//           email: profile?.emailId,
//           isSubUser: profile?.isSubUser || false,
//           TwoNf: profile?.TwoNf || false,
//           allPermissions: formattedPermissions,
//           permissions: formattedPermissions
//         }
        
//         localStorage.setItem(authConfig.storageTokenKeyName, access)
//         localStorage.setItem('refreshToken', refresh)
//         localStorage.setItem('userData', JSON.stringify(userData))
//         localStorage.setItem('isAuthenticated', 'true')
        
//         sessionStorage.setItem(authConfig.storageTokenKeyName, access)
//         sessionStorage.setItem('userData', JSON.stringify(userData))
//         sessionStorage.setItem('isAuthenticated', 'true')
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 2000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//       }
//       else {
//         // Handle error response
//         const errorMessage = response.data?.message || response.data?.content?.message || 'Invalid OTP. Please try again.'
        
//         console.log('Error Message:', errorMessage)
        
//         toast.error(errorMessage, {
//           id: toastId,
//           duration: 5000
//         })
        
//         // Clear all OTP inputs
//         reset(defaultValues)
//       }
//     } catch (error: any) {
//       console.error('=== OTP Verification Error ===')
//       console.error('Error:', error)
//       console.error('Error Response:', error.response?.data)
      
//       // Check if the response actually succeeded but went to catch
//       if (error.response?.data?.access) {
//         const { access, refresh, profile } = error.response.data
        
//         let formattedPermissions = []
//         if (profile?.allPermissions && profile.allPermissions.length > 0) {
//           formattedPermissions = profile.allPermissions
//         } else if (profile?.permissions && profile.permissions.length > 0) {
//           formattedPermissions = profile.permissions
//         } else {
//           formattedPermissions = [
//             { moduleName: 'dashboard', action: 'CREATE' },
//             { moduleName: 'dashboard', action: 'UPDATE' },
//             { moduleName: 'dashboard', action: 'VIEW' },
//             { moduleName: 'dashboard', action: 'DELETE' }
//           ]
//         }
        
//         const userData = {
//           id: profile?.uid,
//           role: profile?.isSubUser ? 'subUser' : 'merchant',
//           fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
//           firstName: profile?.firstName,
//           lastName: profile?.lastName,
//           mobileNum: profile?.mobileNum,
//           username: profile?.emailId,
//           email: profile?.emailId,
//           isSubUser: profile?.isSubUser || false,
//           TwoNf: profile?.TwoNf || false,
//           allPermissions: formattedPermissions,
//           permissions: formattedPermissions
//         }
        
//         localStorage.setItem(authConfig.storageTokenKeyName, access)
//         localStorage.setItem('refreshToken', refresh)
//         localStorage.setItem('userData', JSON.stringify(userData))
//         localStorage.setItem('isAuthenticated', 'true')
        
//         sessionStorage.setItem(authConfig.storageTokenKeyName, access)
//         sessionStorage.setItem('userData', JSON.stringify(userData))
//         sessionStorage.setItem('isAuthenticated', 'true')
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 2000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//         return
//       }
      
//       let errorMessage = 'Verification failed. Please try again.'
      
//       if (error.response?.data?.message) {
//         errorMessage = error.response.data.message
//       } else if (error.response?.data?.content?.message) {
//         errorMessage = error.response.data.content.message
//       } else if (error.response?.data?.detail) {
//         errorMessage = `Error: ${error.response.data.detail}`
//       } else if (error.response?.status === 500) {
//         errorMessage = 'Server error. Please make sure you entered the correct OTP from your authenticator app.'
//       } else if (error.response?.status === 400) {
//         errorMessage = 'Invalid OTP. Please check and try again.'
//       } else if (!error.response) {
//         errorMessage = 'Network error. Please check your connection.'
//       }
      
//       console.log('Error Message:', errorMessage)
      
//       toast.error(errorMessage, {
//         id: toastId,
//         duration: 5000
//       })
      
//       // Clear all OTP inputs
//       reset(defaultValues)
//     } finally {
//       setIsVerifying(false)
//     }
//   }

//   return (
//     <Box sx={{ width: '100%', maxWidth: 400 }}>
//       <Box sx={{ mb: 4, display: 'flex' }}>
//         <img
//           src='/images/website-logo/LockTrust-logo.png'
//           alt='LockTrust Logo'
//           style={{
//             height: '60px',
//             width: 'auto',
//             objectFit: 'contain'
//           }}
//         />
//       </Box>
//       <Box sx={{ my: 6 }}>
//         <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//           Two-Step Verification 💬
//         </Typography>
//         <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//           Please enter the verification code from your authenticator app
//         </Typography>
//         <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
//           {email || sessionStorage.getItem('userEmail') || 'your email address'}
//         </Typography>
//         <Typography sx={{ fontWeight: 500 }}>{mobile}</Typography>
//       </Box>
//       <Typography sx={{ fontWeight: 500, color: 'text.secondary' }}>Type your 6 digit security code</Typography>
//       <form onSubmit={handleSubmit(onSubmit)}>
//         <CleaveWrapper
//           sx={{
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'space-between',
//             ...(errorsArray.length && {
//               '& .invalid:focus': {
//                 borderColor: theme => `${theme.palette.error.main} !important`,
//                 boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//               }
//             })
//           }}
//         >
//           {renderInputs()}
//         </CleaveWrapper>
//         {errorsArray.length ? (
//           <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid OTP</FormHelperText>
//         ) : null}
//         <Button 
//           fullWidth 
//           type='submit' 
//           variant='contained' 
//           sx={{ mt: 2 }}
//           disabled={isVerifying}
//         >
//           {isVerifying ? <CircularProgress size={24} color='inherit' /> : 'Verify My Account'}
//         </Button>
//       </form>
//     </Box>
//   )
// }

// export default VerifyUser




// flow changes ////////////////////////////////////////////////

import { ChangeEvent, useState, KeyboardEvent } from 'react'
import { useRouter } from 'next/router'

// ** MUI Components
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import { styled, useTheme } from '@mui/material/styles'
import FormHelperText from '@mui/material/FormHelperText'
import CircularProgress from '@mui/material/CircularProgress'

// ** Third Party Imports
import Cleave from 'cleave.js/react'
import { useForm, Controller } from 'react-hook-form'
import toast from 'react-hot-toast'

// ** Custom Styled Component
import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// ** Util Import
import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// ** Styles
import 'cleave.js/dist/addons/cleave-phone.us'

// ** Axios
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'
import CryptoJS from 'crypto-js'
import authConfig from 'src/configs/auth'

export type ErrCallbackType = (err: { [key: string]: string }) => void

interface ValuesObject {
  val1: string
  val2: string
  val3: string
  val4: string
  val5: string
  val6: string
}

interface VerifyUserProps {
  token: string
  mobile: string
  email: string
  twoFA: boolean // Add twoFA prop to determine which API to use
}

const CleaveInput = styled(Cleave)(({ theme }) => ({
  maxWidth: 48,
  textAlign: 'center',
  height: '48px !important',
  fontSize: '150% !important',
  marginTop: theme.spacing(2),
  marginBottom: theme.spacing(2),
  '&:not(:last-child)': {
    marginRight: theme.spacing(2)
  },
  '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
    margin: 0,
    WebkitAppearance: 'none'
  }
}))

const defaultValues: { [key: string]: string } = {
  val1: '',
  val2: '',
  val3: '',
  val4: '',
  val5: '',
  val6: ''
}

// AES Encryption function for OTP
const SECRET_KEY = process.env.NEXT_PUBLIC_CRYPTO_SECRET_KEY || ''

const encryptAES = (text: string): string => {
  try {
    const key = CryptoJS.SHA256(SECRET_KEY)
    const iv = CryptoJS.lib.WordArray.random(16)
    const encrypted = CryptoJS.AES.encrypt(text, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    const combined = iv.clone().concat(encrypted.ciphertext)
    return CryptoJS.enc.Base64.stringify(combined)
  } catch (error) {
    console.error('Encryption error:', error)
    return text
  }
}

const VerifyUser = ({ token, mobile, email, twoFA }: VerifyUserProps) => {
  // ** State
  const [isBackspace, setIsBackspace] = useState<boolean>(false)
  const [isVerifying, setIsVerifying] = useState<boolean>(false)
  
  const router = useRouter()

  // ** Hooks
  const theme = useTheme()
  
  const {
    control,
    handleSubmit,
    reset,
    formState: { errors }
  } = useForm<ValuesObject>({ defaultValues })

  // ** Vars
  const errorsArray = Object.keys(errors)

  const handleChange = (event: ChangeEvent, onChange: (...event: any[]) => void) => {
    if (!isBackspace) {
      onChange(event)

      // @ts-ignore
      const form = event.target.form
      const index = [...form].indexOf(event.target)
      if (form[index].value && form[index].value.length) {
        const nextInput = form.elements[index + 1]
        if (nextInput) nextInput.focus()
      }
      event.preventDefault()
    }
  }

  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Backspace') {
      setIsBackspace(true)

      // @ts-ignore
      const form = event.target.form
      const index = [...form].indexOf(event.target)
      if (index >= 1) {
        if (!(form[index].value && form[index].value.length)) {
          const prevInput = form.elements[index - 1]
          if (prevInput) prevInput.focus()
        }
      }
    } else {
      setIsBackspace(false)
    }
  }

  const renderInputs = () => {
    return (Object.keys(defaultValues) as (keyof ValuesObject)[]).map((val, index) => (
      <Controller
        key={val}
        name={val}
        control={control}
        rules={{ required: true }}
        render={({ field: { value, onChange } }) => (
          <Box
            type='tel'
            value={value}
            autoFocus={index === 0}
            component={CleaveInput}
            onKeyDown={handleKeyDown}
            onChange={(event: ChangeEvent) => handleChange(event, onChange)}
            options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
            sx={{ [theme.breakpoints.down('sm')]: { px: `${theme.spacing(2)} !important` } }}
          />
        )}
      />
    ))
  }

  // Helper function to store user data
  const storeUserData = (access: string, refresh: string, profile: any) => {
    // Format permissions
    let formattedPermissions = []
    if (profile?.allPermissions && profile.allPermissions.length > 0) {
      formattedPermissions = profile.allPermissions
    } else if (profile?.permissions && profile.permissions.length > 0) {
      formattedPermissions = profile.permissions.map((p: any) => ({
        moduleName: p.moduleName,
        action: p.action
      }))
    } else {
      formattedPermissions = [
        { moduleName: 'dashboard', action: 'CREATE' },
        { moduleName: 'dashboard', action: 'UPDATE' },
        { moduleName: 'dashboard', action: 'VIEW' },
        { moduleName: 'dashboard', action: 'DELETE' }
      ]
    }

    // Format user data with applicationId
    const userData = {
      id: profile?.uid || profile?.id,
      role: profile?.isSubUser ? 'subUser' : 'merchant',
      fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
      firstName: profile?.firstName,
      lastName: profile?.lastName,
      mobileNum: profile?.mobileNum,
      username: profile?.emailId,
      email: profile?.emailId,
      isSubUser: profile?.isSubUser || false,
      TwoNf: profile?.TwoNf || false,
      isPinSetup: profile?.isPinSetup || false,
      allPermissions: formattedPermissions,
      permissions: formattedPermissions,
      applicationId: profile?.applicationId || profile?.applicationId || null // Add applicationId here
    }
    
    console.log('Storing User Data with applicationId:', userData)
    
    // Store tokens and user data in localStorage
    localStorage.setItem(authConfig.storageTokenKeyName, access)
    localStorage.setItem('refreshToken', refresh)
    localStorage.setItem('userData', JSON.stringify(userData))
    localStorage.setItem('isAuthenticated', 'true')
    
    return userData
  }

  const onSubmit = async (data: ValuesObject) => {
    const otpValue = Object.values(data).join('')
    
    if (otpValue.length !== 6) {
      toast.error('Please enter complete 6-digit code')
      return
    }
    
    setIsVerifying(true)
    const toastId = toast.loading('Verifying OTP...')
    
    try {
      // Encrypt the OTP before sending
      const encryptedOTP = encryptAES(otpValue)
      
      // Choose API endpoint based on twoFA flag
      let endpoint = ''
      if (twoFA) {
        endpoint = `${endpoints.auth.verifyAccount}/${token}`
        console.log('=== 2FA OTP Verification Request ===')
      } else {
        endpoint = `${endpoints.auth.verifyUser}/${token}`
        console.log('=== Mobile OTP Verification Request ===')
      }
      
      // Make API call to verify OTP with encrypted OTP
      const response = await axios.post(endpoint, {
        otp: encryptedOTP
      })
      
      console.log('=== OTP Verification Response ===')
      console.log('Full Response:', response.data)
      
      // Check for successful response - API returns access token and profile
      if (response.data && response.data.access) {
        // Success! Store the tokens
        const { access, refresh, expiresIn, profile } = response.data
        
        console.log('Login Successful! User:', profile?.emailId)
        console.log('User Permissions:', profile?.allPermissions || profile?.permissions)
        console.log('Application ID:', profile?.applicationId)
        
        // Store user data with applicationId
        storeUserData(access, refresh, profile)
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 2000
        })
        
        // Use window.location.href for hard redirect
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
      } 
      else if (response.data?.code === 200 && response.data?.content?.access) {
        // Alternative response structure
        const { access, refresh, profile } = response.data.content
        
        console.log('Application ID:', profile?.applicationId)
        
        // Store user data with applicationId
        storeUserData(access, refresh, profile)
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 2000
        })
        
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
      }
      else {
        // Handle error response
        const errorMessage = response.data?.message || response.data?.content?.message || 'Invalid OTP. Please try again.'
        
        console.log('Error Message:', errorMessage)
        
        toast.error(errorMessage, {
          id: toastId,
          duration: 5000
        })
        
        // Clear all OTP inputs
        reset(defaultValues)
      }
    } catch (error: any) {
      console.error('=== OTP Verification Error ===')
      console.error('Error:', error)
      console.error('Error Response:', error.response?.data)
      
      // Check if the response actually succeeded but went to catch
      if (error.response?.data?.access) {
        const { access, refresh, profile } = error.response.data
        
        console.log('Application ID from catch block:', profile?.applicationId)
        
        // Store user data with applicationId
        storeUserData(access, refresh, profile)
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 2000
        })
        
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
        return
      }
      
      // Check for alternative response structure in catch block
      if (error.response?.data?.content?.access) {
        const { access, refresh, profile } = error.response.data.content
        
        console.log('Application ID from catch block (content):', profile?.applicationId)
        
        // Store user data with applicationId
        storeUserData(access, refresh, profile)
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 2000
        })
        
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
        return
      }
      
      let errorMessage = 'Verification failed. Please try again.'
      
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error.response?.data?.content?.message) {
        errorMessage = error.response.data.content.message
      } else if (error.response?.data?.detail) {
        errorMessage = `Error: ${error.response.data.detail}`
      } else if (error.response?.status === 500) {
        errorMessage = 'Server error. Please make sure you entered the correct OTP.'
      } else if (error.response?.status === 400) {
        errorMessage = 'Invalid OTP. Please check and try again.'
      } else if (!error.response) {
        errorMessage = 'Network error. Please check your connection.'
      }
      
      console.log('Error Message:', errorMessage)
      
      toast.error(errorMessage, {
        id: toastId,
        duration: 5000
      })
      
      // Clear all OTP inputs
      reset(defaultValues)
    } finally {
      setIsVerifying(false)
    }
  }

  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Box sx={{ mb: 4, display: 'flex' }}>
        <img
          src='/images/website-logo/locktrust-logo.png'
          alt='LockTrust Logo'
          style={{
            height: '60px',
            width: 'auto',
            objectFit: 'contain'
          }}
        />
      </Box>
      <Box sx={{ my: 6 }}>
        <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
          {twoFA ? 'Two-Step Verification 💬' : 'Verify Account 💬'}
        </Typography>
        <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
          {twoFA 
            ? 'Please enter the verification code from your authenticator app'
            : 'We sent a verification code to your mobile. Enter the code from the mobile in the field below.'
          }
        </Typography>
        <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
          {email || sessionStorage.getItem('userEmail') || 'your email address'}
        </Typography>
        <Typography sx={{ fontWeight: 500 }}>{mobile}</Typography>
      </Box>
      <Typography sx={{ fontWeight: 500, color: 'text.secondary' }}>Type your 6 digit security code</Typography>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CleaveWrapper
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            ...(errorsArray.length && {
              '& .invalid:focus': {
                borderColor: theme => `${theme.palette.error.main} !important`,
                boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
              }
            })
          }}
        >
          {renderInputs()}
        </CleaveWrapper>
        {errorsArray.length ? (
          <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid OTP</FormHelperText>
        ) : null}
        <Button 
          fullWidth 
          type='submit' 
          variant='contained' 
          sx={{ mt: 2 }}
          disabled={isVerifying}
        >
          {isVerifying ? <CircularProgress size={24} color='inherit' /> : 'Verify My Account'}
        </Button>
      </form>
    </Box>
  )
}

export default VerifyUser