// // ** React Imports
// import { ReactNode, useState, useEffect } from 'react'

// // ** Next Import
// 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 Card from '@mui/material/Card'
// import CardContent from '@mui/material/CardContent'
// import TextField from '@mui/material/TextField'
// import { styled, useTheme } from '@mui/material/styles'
// import Alert from '@mui/material/Alert'
// import Stepper from '@mui/material/Stepper'
// import Step from '@mui/material/Step'
// import StepLabel from '@mui/material/StepLabel'
// import Paper from '@mui/material/Paper'

// // ** Layout Import
// import BlankLayout from 'src/@core/layouts/BlankLayout'

// // ** Third Party Imports
// import { useForm, Controller } from 'react-hook-form'
// import * as yup from 'yup'
// import { yupResolver } from '@hookform/resolvers/yup'

// const CardStyled = styled(Card)(({ theme }) => ({
//   width: '100%',
//   maxWidth: 550,
//   borderRadius: '24px',
//   boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)'
// }))

// const QrCodeBox = styled(Paper)(({ theme }) => ({
//   padding: theme.spacing(3),
//   textAlign: 'center',
//   backgroundColor: theme.palette.grey[50],
//   border: `1px solid ${theme.palette.divider}`,
//   marginBottom: theme.spacing(3)
// }))

// interface Setup2FAFormData {
//   verificationCode: string
// }

// const schema = yup.object().shape({
//   verificationCode: yup.string().required('Verification code is required').length(6, 'Code must be 6 digits')
// })

// const Setup2FA = () => {
//   const theme = useTheme()
//   const router = useRouter()
//   const [activeStep, setActiveStep] = useState(0)
//   const [isSubmitting, setIsSubmitting] = useState(false)
//   const [resendTimer, setResendTimer] = useState(30)
//   const [canResend, setCanResend] = useState(false)

//   const {
//     control,
//     handleSubmit,
//     formState: { errors }
//   } = useForm<Setup2FAFormData>({
//     defaultValues: {
//       verificationCode: ''
//     },
//     mode: 'onBlur',
//     resolver: yupResolver(schema)
//   })

//   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])

//   const handleNext = () => {
//     setActiveStep(1)
//   }

//   const handleResendCode = () => {
//     if (canResend) {
//       setResendTimer(30)
//       setCanResend(false)
//       console.log('Resending verification code...')
//     }
//   }

//   const onSubmit = (data: Setup2FAFormData) => {
//     setIsSubmitting(true)
    
//     // Simulate verification
//     setTimeout(() => {
//       console.log('2FA Setup completed with code:', data.verificationCode)
//       localStorage.setItem('twoFactorEnabled', 'true')
      
//       // Redirect to login after successful registration
//       router.push('/login?registered=true')
      
//       setIsSubmitting(false)
//     }, 1500)
//   }

//   const LogoSVG = () => (
//     <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
//       <rect width="48" height="48" rx="12" fill="url(#gradient)" />
//       <path d="M24 12L28 18H20L24 12Z" fill="white" />
//       <path d="M24 36L20 30H28L24 36Z" fill="white" />
//       <path d="M14 20L20 24L14 28V20Z" fill="white" />
//       <path d="M34 28L28 24L34 20V28Z" fill="white" />
//       <path d="M24 22L28 24L24 26L20 24L24 22Z" fill="white" fillOpacity="0.8" />
//       <defs>
//         <linearGradient id="gradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
//           <stop stopColor="#6366F1" />
//           <stop offset="1" stopColor="#8B5CF6" />
//         </linearGradient>
//       </defs>
//     </svg>
//   )

//   return (
//     <Box
//       sx={{
//         width: '100%',
//         minHeight: '100vh',
//         display: 'flex',
//         alignItems: 'center',
//         justifyContent: 'center',
//         py: 8,
//         px: 2,
//         background: `linear-gradient(135deg, ${theme.palette.background.default} 0%, ${theme.palette.background.paper} 100%)`
//       }}
//     >
//       <CardStyled>
//         <Box
//           sx={{
//             background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
//             color: 'white',
//             p: 4,
//             textAlign: 'center'
//           }}
//         >
//           <Box sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
//             <LogoSVG />
//           </Box>
//           <Typography variant="h5" sx={{ fontWeight: 700, mb: 1, color: 'white' }}>
//             Enable two-factor auth
//           </Typography>
//           <Typography variant="body2" sx={{ opacity: 0.9, color: 'white' }}>
//             Scan the QR code with Google Authenticator or Authy to get started.
//           </Typography>
//         </Box>

//         <CardContent sx={{ p: 4 }}>
//           <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
//             <Step>
//               <StepLabel>Scan QR</StepLabel>
//             </Step>
//             <Step>
//               <StepLabel>Verify code</StepLabel>
//             </Step>
//             <Step>
//               <StepLabel>Done</StepLabel>
//             </Step>
//           </Stepper>

//           {activeStep === 0 ? (
//             <Box>
//               <Alert severity="info" sx={{ mb: 3 }}>
//                 Open your authenticator app and scan this QR code
//               </Alert>

//               <QrCodeBox>
//                 {/* Simulated QR Code */}
//                 <Box
//                   sx={{
//                     width: 200,
//                     height: 200,
//                     margin: '0 auto',
//                     backgroundColor: theme.palette.common.white,
//                     display: 'flex',
//                     alignItems: 'center',
//                     justifyContent: 'center',
//                     border: `2px solid ${theme.palette.divider}`,
//                     mb: 2
//                   }}
//                 >
//                   <Typography variant="caption" sx={{ textAlign: 'center' }}>
//                     [QR Code Simulated]
//                     <br />
//                     Scan with Authenticator
//                   </Typography>
//                 </Box>
                
//                 <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
//                   Can't scan? Enter this secret key manually:
//                 </Typography>
//                 <Paper
//                   sx={{
//                     p: 2,
//                     backgroundColor: theme.palette.grey[100],
//                     fontFamily: 'monospace',
//                     letterSpacing: 2
//                   }}
//                 >
//                   HWD4 SNFY KDUK JPWQ
//                 </Paper>
//               </QrCodeBox>

//               <Button
//                 fullWidth
//                 size='large'
//                 variant='contained'
//                 onClick={handleNext}
//                 sx={{ mt: 2, py: 1.5 }}
//               >
//                 I've scanned the code →
//               </Button>
//             </Box>
//           ) : (
//             <Box>
//               <Alert severity="info" sx={{ mb: 3 }}>
//                 Enter the 6-digit code from your authenticator app
//               </Alert>

//               <form onSubmit={handleSubmit(onSubmit)}>
//                 <Controller
//                   name='verificationCode'
//                   control={control}
//                   render={({ field }) => (
//                     <TextField
//                       {...field}
//                       fullWidth
//                       label='Verification code'
//                       placeholder='000000'
//                       error={!!errors.verificationCode}
//                       helperText={errors.verificationCode?.message}
//                       inputProps={{ maxLength: 6 }}
//                       sx={{ mb: 3 }}
//                       required
//                     />
//                   )}
//                 />

//                 <Button
//                   fullWidth
//                   size='large'
//                   type='submit'
//                   variant='contained'
//                   disabled={isSubmitting}
//                   sx={{ py: 1.5 }}
//                 >
//                   {isSubmitting ? 'Verifying...' : 'Verify & Complete →'}
//                 </Button>

//                 <Box sx={{ mt: 2, textAlign: 'center' }}>
//                   <Typography variant='caption' sx={{ color: 'text.secondary' }}>
//                     Didn't receive code?{' '}
//                     <Button
//                       variant='text'
//                       size='small'
//                       onClick={handleResendCode}
//                       disabled={!canResend}
//                       sx={{ textTransform: 'none' }}
//                     >
//                       {canResend ? 'Resend' : `Resend in ${resendTimer}s`}
//                     </Button>
//                   </Typography>
//                 </Box>
//               </form>
//             </Box>
//           )}
//         </CardContent>
//       </CardStyled>
//     </Box>
//   )
// }

// Setup2FA.getLayout = (page: ReactNode) => <BlankLayout>{page}</BlankLayout>
// Setup2FA.guestGuard = true

// export default Setup2FA


// ** React Imports
import { ReactNode, useState, useEffect } from 'react'

// ** Next Import
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 Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import TextField from '@mui/material/TextField'
import { styled, useTheme } from '@mui/material/styles'
import Alert from '@mui/material/Alert'
import Stepper from '@mui/material/Stepper'
import Step from '@mui/material/Step'
import StepLabel from '@mui/material/StepLabel'
import Paper from '@mui/material/Paper'

// ** Layout Import
import BlankLayout from 'src/@core/layouts/BlankLayout'

// ** Third Party Imports
import { useForm, Controller } from 'react-hook-form'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import toast from 'react-hot-toast'

// ** Next & Axios
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'

// ** Third party Loader
import { BeatLoader } from 'react-spinners'

const CardStyled = styled(Card)(({ theme }) => ({
  width: '100%',
  maxWidth: 550,
  borderRadius: '24px',
  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)'
}))

const QrCodeBox = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(3),
  textAlign: 'center',
  backgroundColor: theme.palette.grey[50],
  border: `1px solid ${theme.palette.divider}`,
  marginBottom: theme.spacing(3)
}))

interface Setup2FAFormData {
  verificationCode: string
}

const schema = yup.object().shape({
  verificationCode: yup.string().required('Verification code is required').length(6, 'Code must be 6 digits')
})

const Setup2FA = () => {
  const theme = useTheme()
  const router = useRouter()
  const [activeStep, setActiveStep] = useState(0)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isGenerating, setIsGenerating] = useState(false)
  const [resendTimer, setResendTimer] = useState(30)
  const [canResend, setCanResend] = useState(false)
  const [qrCodeBase64, setQrCodeBase64] = useState<string>('')
  const [secretKey, setSecretKey] = useState<string>('')
  const [userEmail, setUserEmail] = useState<string>('')

  const {
    control,
    handleSubmit,
    formState: { errors }
  } = useForm<Setup2FAFormData>({
    defaultValues: {
      verificationCode: ''
    },
    mode: 'onBlur',
    resolver: yupResolver(schema)
  })

  // Get email from sessionStorage on component mount
  useEffect(() => {
    const email = sessionStorage.getItem('Email')
    if (email) {
      setUserEmail(email)
      generateQRCode(email)
    } else {
      // If no email found, redirect to login
      toast.error('Session expired. Please login again.')
      router.push('/login')
    }
  }, [])

  // 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])

  // Generate QR Code API call
  const generateQRCode = async (email: string) => {
    setIsGenerating(true)
    try {
      const response = await axios.post(endpoints.auth.generate2FA, {
        email: email
      })

      console.log('QR Code Response:', response.data)

      // Handle the actual response structure
      if (response.data) {
        const { qr_code_base64, message } = response.data
        
        if (qr_code_base64) {
          setQrCodeBase64(qr_code_base64)
          toast.success(message || 'QR code generated successfully!', {
            duration: 4000
          })
        } else {
          toast.error('Invalid response: QR code not found', {
            duration: 5000
          })
        }
      } else {
        const errorMessage = typeof response.data === 'string' 
          ? response.data 
          : response.data?.message || 'Failed to generate QR code'
        
        toast.error(errorMessage, {
          duration: 5000
        })
      }
    } catch (error: any) {
      console.error('Error generating QR code:', error)
      
      let errorMessage = 'Failed to generate QR code. Please try again.'
      
      if (error.response?.data) {
        if (typeof error.response.data === 'string') {
          errorMessage = error.response.data
        } else if (error.response.data.message) {
          errorMessage = error.response.data.message
        } else if (error.response.data.content) {
          errorMessage = typeof error.response.data.content === 'string' 
            ? error.response.data.content 
            : error.response.data.content.message || errorMessage
        }
      } else if (!error.response) {
        errorMessage = 'Network error. Please check your connection.'
      }
      
      toast.error(errorMessage, {
        duration: 5000
      })
    } finally {
      setIsGenerating(false)
    }
  }

  const handleNext = () => {
    setActiveStep(1)
  }

  const handleResendCode = () => {
    if (canResend && userEmail) {
      setResendTimer(30)
      setCanResend(false)
      generateQRCode(userEmail)
    }
  }

  const onSubmit = async (data: Setup2FAFormData) => {
    setIsSubmitting(true)
    
    try {
      const response = await axios.post(endpoints.auth.verify2FA, {
        email: userEmail,
        otp: data.verificationCode
      })

      console.log('Verify Response:', response.data)

      // Handle the actual response structure
      if (response.data) {
        // Check for success message or any positive response
        const isSuccess = response.data.message?.toLowerCase().includes('success') || 
                         response.data.success === true || 
                         response.data.code === 200 ||
                         response.data.status === 'success'
        
        if (isSuccess) {
          toast.success(response.data.message || '2FA enabled successfully!', {
            duration: 4000
          })
          
          // Store 2FA enabled status
          localStorage.setItem('twoFactorEnabled', 'true')
          
          // Clear session storage email
          sessionStorage.removeItem('Email')
          sessionStorage.removeItem('requiresVerification')
          
          // Redirect to login after successful registration
          router.push('/login?registered=true&twofa=enabled')
        } else {
          const errorMessage = response.data.message || 'Verification failed'
          toast.error(errorMessage, {
            duration: 5000
          })
        }
      } else {
        toast.error('Verification failed. Please try again.', {
          duration: 5000
        })
      }
    } catch (error: any) {
      console.error('Error verifying OTP:', error)
      
      let errorMessage = 'Verification failed. Please try again.'
      
      if (error.response?.data) {
        if (typeof error.response.data === 'string') {
          errorMessage = error.response.data
        } else if (error.response.data.message) {
          errorMessage = error.response.data.message
        } else if (error.response.data.content) {
          errorMessage = typeof error.response.data.content === 'string' 
            ? error.response.data.content 
            : error.response.data.content.message || errorMessage
        }
      } else if (error.response?.status === 400) {
        errorMessage = 'Invalid verification code. Please try again.'
      } else if (!error.response) {
        errorMessage = 'Network error. Please check your connection.'
      }
      
      toast.error(errorMessage, {
        duration: 5000
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const LogoSVG = () => (
    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect width="48" height="48" rx="12" fill="url(#gradient)" />
      <path d="M24 12L28 18H20L24 12Z" fill="white" />
      <path d="M24 36L20 30H28L24 36Z" fill="white" />
      <path d="M14 20L20 24L14 28V20Z" fill="white" />
      <path d="M34 28L28 24L34 20V28Z" fill="white" />
      <path d="M24 22L28 24L24 26L20 24L24 22Z" fill="white" fillOpacity="0.8" />
      <defs>
        <linearGradient id="gradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
          <stop stopColor="#6366F1" />
          <stop offset="1" stopColor="#8B5CF6" />
        </linearGradient>
      </defs>
    </svg>
  )

  return (
    <Box
      sx={{
        width: '100%',
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        py: 8,
        px: 2,
        background: `linear-gradient(135deg, ${theme.palette.background.default} 0%, ${theme.palette.background.paper} 100%)`
      }}
    >
      <CardStyled>
        <Box
          sx={{
            background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
            color: 'white',
            p: 4,
            textAlign: 'center'
          }}
        >
          <Box sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
            <LogoSVG />
          </Box>
          <Typography variant="h5" sx={{ fontWeight: 700, mb: 1, color: 'white' }}>
            Enable two-factor auth
          </Typography>
          <Typography variant="body2" sx={{ opacity: 0.9, color: 'white' }}>
            Scan the QR code with Google Authenticator or Authy to get started.
          </Typography>
        </Box>

        <CardContent sx={{ p: 4 }}>
          <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
            <Step>
              <StepLabel>Scan QR</StepLabel>
            </Step>
            <Step>
              <StepLabel>Verify code</StepLabel>
            </Step>
            <Step>
              <StepLabel>Done</StepLabel>
            </Step>
          </Stepper>

          {activeStep === 0 ? (
            <Box>
              <Alert severity="info" sx={{ mb: 3 }}>
                Open your authenticator app and scan this QR code
              </Alert>

              {isGenerating ? (
                <Box sx={{ textAlign: 'center', py: 8 }}>
                  <BeatLoader size={15} color={theme.palette.primary.main} />
                  <Typography sx={{ mt: 2 }}>Generating QR Code...</Typography>
                </Box>
              ) : (
                <>
                  <QrCodeBox>
                    {qrCodeBase64 ? (
                      <>
                        <Box
                          sx={{
                            width: 200,
                            height: 200,
                            margin: '0 auto',
                            backgroundColor: theme.palette.common.white,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            border: `2px solid ${theme.palette.divider}`,
                            mb: 2,
                            overflow: 'hidden',
                            borderRadius: 2
                          }}
                        >
                          <img 
                            src={`data:image/png;base64,${qrCodeBase64}`}
                            alt="QR Code"
                            style={{ width: '100%', height: '100%', objectFit: 'contain' }}
                          />
                        </Box>
                        
                        {secretKey && (
                          <>
                            <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
                              Can't scan? Enter this secret key manually:
                            </Typography>
                            <Paper
                              sx={{
                                p: 2,
                                backgroundColor: theme.palette.grey[100],
                                fontFamily: 'monospace',
                                letterSpacing: 2,
                                textAlign: 'center',
                                wordBreak: 'break-all'
                              }}
                            >
                              {secretKey}
                            </Paper>
                          </>
                        )}
                      </>
                    ) : (
                      <Typography color="error">Failed to load QR code. Please try again.</Typography>
                    )}
                  </QrCodeBox>

                  <Button
                    fullWidth
                    size='large'
                    variant='contained'
                    onClick={handleNext}
                    disabled={!qrCodeBase64}
                    sx={{ mt: 2, py: 1.5 }}
                  >
                    I've scanned the code →
                  </Button>
                </>
              )}
            </Box>
          ) : (
            <Box>
              <Alert severity="info" sx={{ mb: 3 }}>
                Enter the 6-digit code from your authenticator app
              </Alert>

              <form onSubmit={handleSubmit(onSubmit)}>
                <Controller
                  name='verificationCode'
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Verification code'
                      placeholder='000000'
                      error={!!errors.verificationCode}
                      helperText={errors.verificationCode?.message}
                      inputProps={{ maxLength: 6 }}
                      sx={{ mb: 3 }}
                      required
                      autoComplete='off'
                    />
                  )}
                />

                <Button
                  fullWidth
                  size='large'
                  type='submit'
                  variant='contained'
                  disabled={isSubmitting}
                  sx={{ py: 1.5 }}
                >
                  {isSubmitting ? <BeatLoader size={15} color='#ffffff' /> : 'Verify & Complete →'}
                </Button>

                <Box sx={{ mt: 2, textAlign: 'center' }}>
                  <Typography variant='caption' sx={{ color: 'text.secondary' }}>
                    Didn't receive code?{' '}
                    <Button
                      variant='text'
                      size='small'
                      onClick={handleResendCode}
                      disabled={!canResend}
                      sx={{ textTransform: 'none' }}
                    >
                      {canResend ? 'Resend' : `Resend in ${resendTimer}s`}
                    </Button>
                  </Typography>
                </Box>
              </form>
            </Box>
          )}
        </CardContent>
      </CardStyled>
    </Box>
  )
}

Setup2FA.getLayout = (page: ReactNode) => <BlankLayout>{page}</BlankLayout>
Setup2FA.guestGuard = true

export default Setup2FA