// import { useState, ReactNode } from 'react'

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

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

// // ** Hooks
// import { useSettings } from 'src/@core/hooks/useSettings'

// import { AnimatePresence, motion } from 'motion/react'

// // ** Configs
// import themeConfig from 'src/configs/themeConfig'

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

// // ** Demo Imports
// import FooterIllustrationsV2 from 'src/views/pages/auth/FooterIllustrationsV2'
// import DocumentVerifyForm from 'src/views/pages/document-verify/DocumentVerifyForm'

// // ** Styled Components
// const DocumentVerifyIllustration = styled('img')(({ theme }) => ({
//   zIndex: 2,
//   maxHeight: 680,
//   marginTop: theme.spacing(12),
//   marginBottom: theme.spacing(12),
//   [theme.breakpoints.down(1540)]: {
//     maxHeight: 550
//   },
//   [theme.breakpoints.down('lg')]: {
//     maxHeight: 500
//   }
// }))

// const RightWrapper = styled(Box)<BoxProps>(({ theme }) => ({
//   width: '100%',
//   [theme.breakpoints.up('md')]: {
//     maxWidth: 550
//   },
//   [theme.breakpoints.up('lg')]: {
//     maxWidth: 650
//   },
//   [theme.breakpoints.up('xl')]: {
//     maxWidth: 800
//   }
// }))

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   color: theme.palette.primary.main,
//   cursor: 'pointer',
//   fontWeight: 500
// }))

// const slideVariants = {
//   hiddenLeft: { x: -400, opacity: 0 },
//   visible: { x: 0, opacity: 1 },
//   exitLeft: { x: -400, opacity: 0 }
// }

// const DocumentVerifyPage = () => {
//   // ** Hooks
//   const theme = useTheme()
//   const { settings } = useSettings()
//   const hidden = useMediaQuery(theme.breakpoints.down('md'))

//   // ** Vars
//   const { skin } = settings

//   const imageSource =
//     skin === 'bordered' ? 'auth-v2-login-illustration-bordered' : 'auth-v2-login-illustration'

//   const handleSubmitDocuments = (data: any) => {
//     console.log('Documents submitted:', data)
//     // Here you can handle the submission to your backend
//   }

//   return (
//     <Box className='content-right' sx={{ backgroundColor: 'background.paper', minHeight: '100vh' }}>
//       {!hidden ? (
//         <Box
//           sx={{
//             flex: 1,
//             display: 'flex',
//             position: 'relative',
//             alignItems: 'center',
//             borderRadius: '20px',
//             justifyContent: 'center',
//             backgroundColor: 'customColors.bodyBg',
//             margin: theme => theme.spacing(8, 0, 8, 8)
//           }}
//         >
//           <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
//             <motion.div
//               key='document-verify'
//               initial={{ opacity: 0 }}
//               animate={{ opacity: 1 }}
//               transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
//               style={{
//                 position: 'absolute',
//                 width: '100%',
//                 height: '100%',
//                 display: 'flex',
//                 justifyContent: 'center',
//                 alignItems: 'center'
//               }}
//             >
//               <DocumentVerifyIllustration
//                 alt='document-verify-illustration'
//                 src={`/images/pages/${imageSource}-${theme.palette.mode}.png`}
//               />
//             </motion.div>
//           </Box>
//           <FooterIllustrationsV2 />
//         </Box>
//       ) : null}

//       <RightWrapper>
//         <Box
//           sx={{
//             p: [6, 12],
//             height: '100%',
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'center'
//           }}
//         >
//           <motion.div
//             key='form'
//             initial='hiddenLeft'
//             animate='visible'
//             exit='exitLeft'
//             variants={slideVariants}
//             transition={{ duration: 0.5 }}
//             style={{ width: '100%' }}
//           >
//             <Box sx={{ mb: 4, display: 'flex', justifyContent: 'center' }}>
//               <img
//                 src='/images/website-logo/LockTrust-logo.png'
//                 alt='LockTrust Logo'
//                 style={{
//                   height: '60px',
//                   width: 'auto',
//                   objectFit: 'contain'
//                 }}
//               />
//             </Box>
            
//             <Box sx={{ width: '100%', maxWidth: 600, mx: 'auto' }}>
//               <Box sx={{ my: 6, textAlign: 'center' }}>
//                 <Typography sx={{ mb: 1.5, fontWeight: 600, fontSize: '1.75rem', lineHeight: 1.385 }}>
//                   Document Verification
//                 </Typography>
//                 <Typography sx={{ color: 'text.secondary' }}>
//                   Verify your identity to complete KYC verification
//                 </Typography>
//               </Box>

//               <DocumentVerifyForm onSubmit={handleSubmitDocuments} />
//             </Box>
//           </motion.div>
//         </Box>
//       </RightWrapper>
//     </Box>
//   )
// }

// DocumentVerifyPage.getLayout = (page: ReactNode) => <BlankLayout>{page}</BlankLayout>

// DocumentVerifyPage.guestGuard = true

// export default DocumentVerifyPage

// final /////////////////////
import { useState, ReactNode, useEffect } from 'react'

// ** Next Import
import Link from 'next/link'
import { useRouter } from 'next/router'

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

// ** Hooks
import { useSettings } from 'src/@core/hooks/useSettings'

import { motion } from 'motion/react'

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

// ** Demo Imports
import FooterIllustrationsV2 from 'src/views/pages/auth/FooterIllustrationsV2'
import DocumentVerifyForm from 'src/views/pages/document-verify/DocumentVerifyForm'

// ** Styled Components
const DocumentVerifyIllustration = styled('img')(({ theme }) => ({
  zIndex: 2,
  maxHeight: 680,
  marginTop: theme.spacing(12),
  marginBottom: theme.spacing(12),
  [theme.breakpoints.down(1540)]: {
    maxHeight: 550
  },
  [theme.breakpoints.down('lg')]: {
    maxHeight: 500
  }
}))

const RightWrapper = styled(Box)<BoxProps>(({ theme }) => ({
  width: '100%',
  [theme.breakpoints.up('md')]: {
    maxWidth: 550
  },
  [theme.breakpoints.up('lg')]: {
    maxWidth: 650
  },
  [theme.breakpoints.up('xl')]: {
    maxWidth: 800
  }
}))

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   color: theme.palette.primary.main,
//   cursor: 'pointer',
//   fontWeight: 500
// }))

const slideVariants = {
  hiddenLeft: { x: -400, opacity: 0 },
  visible: { x: 0, opacity: 1 },
  exitLeft: { x: -400, opacity: 0 }
}

const DocumentVerifyPage = () => {
  const theme = useTheme()
  const { settings } = useSettings()
  const hidden = useMediaQuery(theme.breakpoints.down('md'))
  const router = useRouter()

  const [businessType, setBusinessType] = useState<string | null>(null)
  const [verificationToken, setVerificationToken] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string>('')

  const { skin } = settings

  // const imageSource =
  //   skin === 'bordered' ? 'auth-v2-login-illustration-bordered' : 'auth-v2-login-illustration'

  useEffect(() => {
    // Wait for router to be ready
    if (!router.isReady) {
      return
    }

    const { token, businessType: queryBusinessType } = router.query

    // Try to get from query params first
    let finalToken = token as string | undefined
    let finalBusinessType = queryBusinessType as string | undefined

    // If not in query, try sessionStorage as fallback
    if (!finalToken) {
      finalToken = sessionStorage.getItem('verificationToken') || undefined
    }
    if (!finalBusinessType) {
      finalBusinessType = sessionStorage.getItem('businessType') || undefined
    }

    console.log('📋 Document Verify - Token:', finalToken)
    console.log('📋 Document Verify - Business Type:', finalBusinessType)

    // Validate - if either is missing, redirect to login
    if (!finalToken || !finalBusinessType) {
      console.error('Missing required verification data:', { finalToken, finalBusinessType })
      setError('Missing verification data. Please complete email verification first.')
      setLoading(false)
      setTimeout(() => {
        router.push('/login')
      }, 3000)
      return
    }

    // Store in sessionStorage for future use
    sessionStorage.setItem('verificationToken', finalToken)
    sessionStorage.setItem('businessType', finalBusinessType)

    setVerificationToken(finalToken)
    setBusinessType(finalBusinessType)
    setLoading(false)
  }, [router.isReady, router.query, router])

  const handleSubmitDocuments = (data: any) => {
    console.log('Documents submitted:', data)
    console.log('Business Type:', businessType)
    console.log('Verification Token:', verificationToken)
  }

  if (loading) {
    return (
      <Box className='content-right' sx={{ backgroundColor: 'background.paper', minHeight: '100vh' }}>
        <RightWrapper>
          <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress size={60} />
              <Typography sx={{ mt: 4, color: 'text.secondary' }}>
                Loading verification...
              </Typography>
            </Box>
          </Box>
        </RightWrapper>
      </Box>
    )
  }

  if (error) {
    return (
      <Box className='content-right' sx={{ backgroundColor: 'background.paper', minHeight: '100vh' }}>
        <RightWrapper>
          <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Box sx={{ textAlign: 'center', maxWidth: 400 }}>
              <Alert severity="error" sx={{ mb: 3 }}>
                {error}
              </Alert>
              <Typography sx={{ color: 'text.secondary', mb: 2 }}>
                Redirecting to login...
              </Typography>
              <Button 
                variant="contained" 
                onClick={() => router.push('/login')}
              >
                Go to Login
              </Button>
            </Box>
          </Box>
        </RightWrapper>
      </Box>
    )
  }

  return (
    <Box className='content-right' sx={{ backgroundColor: 'background.paper', minHeight: '100vh' }}>
      {!hidden ? (
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            position: 'relative',
            alignItems: 'center',
            borderRadius: '20px',
            justifyContent: 'center',
            backgroundColor: 'customColors.bodyBg',
            margin: theme => theme.spacing(8, 0, 8, 8)
          }}
        >
          <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
            <motion.div
              key='document-verify'
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
              style={{
                position: 'absolute',
                width: '100%',
                height: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <DocumentVerifyIllustration
                alt='document-verify-illustration'
                src={`/images/pages/document verify.png`}
              />
            </motion.div>
          </Box>
          <FooterIllustrationsV2 />
        </Box>
      ) : null}

      <RightWrapper>
        <Box
          sx={{
            p: [6, 12],
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <motion.div
            key='form'
            initial='hiddenLeft'
            animate='visible'
            exit='exitLeft'
            variants={slideVariants}
            transition={{ duration: 0.5 }}
            style={{ width: '100%' }}
          >
            <Box sx={{ mb: 4, display: 'flex', justifyContent: 'center' }}>
              <img
                src='/images/website-logo/locktrust-logo.png'
                alt='LockTrust Logo'
                style={{
                  height: '60px',
                  width: 'auto',
                  objectFit: 'contain'
                }}
              />
            </Box>
            
            <Box sx={{ width: '100%', maxWidth: 600, mx: 'auto' }}>
              <Box sx={{ my: 6, textAlign: 'center' }}>
                <Typography sx={{ mb: 1.5, fontWeight: 600, fontSize: '1.75rem', lineHeight: 1.385 }}>
                  Document Verification
                </Typography>
                <Typography sx={{ color: 'text.secondary' }}>
                  {businessType?.toLowerCase() === 'business' 
                    ? 'Verify your business identity to complete KYC verification' 
                    : 'Verify your identity to complete KYC verification'}
                </Typography>
                {businessType && (
                  <Typography sx={{ mt: 1, color: 'primary.main', fontWeight: 500 }}>
                    Account Type: {businessType}
                  </Typography>
                )}
                {/* {verificationToken && (
                  <Typography sx={{ mt: 0.5, color: 'text.secondary', fontSize: '0.75rem' }}>
                    Token: {verificationToken.substring(0, 20)}...
                  </Typography>
                )} */}
              </Box>

              <DocumentVerifyForm 
                onSubmit={handleSubmitDocuments} 
                businessType={businessType}
                verificationToken={verificationToken}
              />
            </Box>
          </motion.div>
        </Box>
      </RightWrapper>
    </Box>
  )
}

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

export default DocumentVerifyPage