// ** 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 CircularProgress from '@mui/material/CircularProgress'
import Divider from '@mui/material/Divider'

// ** 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)'
}))

interface VerifyFormData {
  phoneOtp: string
  emailOtp: string
}

const schema = yup.object().shape({
  phoneOtp: yup.string().required('Phone OTP is required').length(6, 'OTP must be 6 digits'),
  emailOtp: yup.string().required('Email OTP is required').length(6, 'OTP must be 6 digits')
})

const VerifyAccount = () => {
  const theme = useTheme()
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [phoneResendTimer, setPhoneResendTimer] = useState(18)
  const [emailResendTimer, setEmailResendTimer] = useState(18)
  const [canResendPhone, setCanResendPhone] = useState(false)
  const [canResendEmail, setCanResendEmail] = useState(false)
  const [phoneVerified, setPhoneVerified] = useState(false)
  const [emailVerified, setEmailVerified] = useState(false)

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

  useEffect(() => {
    let phoneTimer: NodeJS.Timeout
    let emailTimer: NodeJS.Timeout

    if (phoneResendTimer > 0 && !canResendPhone) {
      phoneTimer = setTimeout(() => setPhoneResendTimer(phoneResendTimer - 1), 1000)
    } else if (phoneResendTimer === 0) {
      setCanResendPhone(true)
    }

    if (emailResendTimer > 0 && !canResendEmail) {
      emailTimer = setTimeout(() => setEmailResendTimer(emailResendTimer - 1), 1000)
    } else if (emailResendTimer === 0) {
      setCanResendEmail(true)
    }

    return () => {
      clearTimeout(phoneTimer)
      clearTimeout(emailTimer)
    }
  }, [phoneResendTimer, emailResendTimer, canResendPhone, canResendEmail])

  const handleResendPhone = () => {
    if (canResendPhone) {
      setPhoneResendTimer(18)
      setCanResendPhone(false)
      console.log('Resending phone verification code...')
    }
  }

  const handleResendEmail = () => {
    if (canResendEmail) {
      setEmailResendTimer(18)
      setCanResendEmail(false)
      console.log('Resending email verification code...')
    }
  }

  const handleVerifyPhone = () => {
    // Simulate phone verification
    setPhoneVerified(true)
  }

  const handleVerifyEmail = () => {
    // Simulate email verification
    setEmailVerified(true)
  }

  const onSubmit = (data: VerifyFormData) => {
    if (!phoneVerified || !emailVerified) {
      return
    }
    
    setIsSubmitting(true)
    
    // Store verification status
    localStorage.setItem('phoneVerified', 'true')
    localStorage.setItem('emailVerified', 'true')
    
    // Redirect to 2FA setup
    setTimeout(() => {
      router.push('/setup-2fa')
      setIsSubmitting(false)
    }, 1000)
  }

  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' }}>
            Verify phone & email
          </Typography>
          <Typography variant="body2" sx={{ opacity: 0.9, color: 'white' }}>
            Codes have been sent to your registered contacts. Verify both to continue.
          </Typography>
        </Box>

        <CardContent sx={{ p: 4 }}>
          <form onSubmit={handleSubmit(onSubmit)}>
            {/* PHONE VERIFICATION */}
            <Box sx={{ mb: 4 }}>
              <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
                PHONE VERIFICATION
              </Typography>
              
              <Typography variant="body2" sx={{ mb: 2, color: 'text.secondary' }}>
                Phone number: <strong>+1 888-888-8888</strong>
              </Typography>
              
              <Controller
                name='phoneOtp'
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label='Phone OTP'
                    placeholder='• • • • • •'
                    error={!!errors.phoneOtp}
                    helperText={errors.phoneOtp?.message}
                    inputProps={{ maxLength: 6 }}
                    sx={{ mb: 2 }}
                    required
                  />
                )}
              />
              
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Typography variant='caption' sx={{ color: 'text.secondary' }}>
                  Resend in {phoneResendTimer}s
                </Typography>
                <Button
                  variant='text'
                  size='small'
                  onClick={handleVerifyPhone}
                  disabled={phoneVerified}
                  sx={{ textTransform: 'none' }}
                >
                  {phoneVerified ? '✓ Verified' : 'Verify phone'}
                </Button>
              </Box>
            </Box>

            <Divider sx={{ my: 3 }} />

            {/* EMAIL VERIFICATION */}
            <Box sx={{ mb: 4 }}>
              <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
                EMAIL VERIFICATION
              </Typography>
              
              <Typography variant="body2" sx={{ mb: 2, color: 'text.secondary' }}>
                Email address: <strong>user@example.com</strong>
              </Typography>
              
              <Controller
                name='emailOtp'
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label='Email OTP'
                    placeholder='• • • • • •'
                    error={!!errors.emailOtp}
                    helperText={errors.emailOtp?.message}
                    inputProps={{ maxLength: 6 }}
                    sx={{ mb: 2 }}
                    required
                  />
                )}
              />
              
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Typography variant='caption' sx={{ color: 'text.secondary' }}>
                  Resend in {emailResendTimer}s
                </Typography>
                <Button
                  variant='text'
                  size='small'
                  onClick={handleVerifyEmail}
                  disabled={emailVerified}
                  sx={{ textTransform: 'none' }}
                >
                  {emailVerified ? '✓ Verified' : 'Verify email'}
                </Button>
              </Box>
            </Box>

            <Button
              fullWidth
              size='large'
              type='submit'
              variant='contained'
              disabled={isSubmitting || !phoneVerified || !emailVerified}
              sx={{ mt: 2, py: 1.5 }}
            >
              {isSubmitting ? <CircularProgress size={24} color='inherit' /> : 'Continue →'}
            </Button>

            {(!phoneVerified || !emailVerified) && (
              <Alert severity="warning" sx={{ mt: 3 }}>
                Please verify both phone and email to continue
              </Alert>
            )}
          </form>
        </CardContent>
      </CardStyled>
    </Box>
  )
}

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

export default VerifyAccount