'use client';

import { useEffect, useState, useCallback, useRef } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton';
import Card from '@mui/material/Card';
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import { paths } from '@/routes/paths';
import { axiosInstancee } from '@/utils/axios';
import Iconify from '@/shared/components/iconify';
import Button from '@mui/material/Button';


export default function VerifyEmail() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams?.get('token');
  const [status, setStatus] = useState<'idle' | 'verifying' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');
  const verificationAttempted = useRef(false);


  const verifyEmail = useCallback(async () => {
    if (!token || verificationAttempted.current) {
      return;
    }

    try {
      setStatus('verifying');
      verificationAttempted.current = true;

      const response = await axiosInstancee.get(`/api/user/confirm?token=${token}`, {
        // Prevent default error handling
        validateStatus: null,
        // Add signal to prevent request cancellation
        signal: new AbortController().signal
      });
    
      setStatus('success');
      setMessage(response.data.message || 'Email verified successfully!');
      
    } catch (error: any) {
    
      setStatus('error');
      setMessage(error.response?.data?.message || 'Verification failed. Please try again.');
      
      // Stop propagation of the error
      if (error.preventDefault) {
        error.preventDefault();
      }
      if (error.stopPropagation) {
        error.stopPropagation();
      }
    }
  }, [token]);

  useEffect(() => {
    if (status === 'idle') {
      verifyEmail();
    }
  }, [status, verifyEmail]);

  useEffect(() => {
    const preventUnload = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', preventUnload);
    return () => {
      window.removeEventListener('beforeunload', preventUnload);
    };
  }, [status]);

  const handleRedirectToLogin = () => {
    router.push(paths.auth.jwt.login);
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        p: 3,
      }}
    >
      <Container maxWidth="sm">
        <Card sx={{ p: 5, textAlign: 'center' }}>
          <Stack spacing={3}>
            {/* Icon */}
            <Iconify
              icon={
                status === 'success'
                  ? 'eva:checkmark-circle-2-fill'
                  : status === 'error'
                  ? 'eva:alert-circle-fill'
                  : 'eva:email-outline'
              }
              sx={{
                width: 96,
                height: 96,
                margin: 'auto',
                color:
                  status === 'success'
                    ? 'success.main'
                    : status === 'error'
                    ? 'error.main'
                    : 'primary.main',
              }}
            />

            {/* Title */}
            <Typography variant="h3">
              {status === 'idle' || status === 'verifying'
                ? 'Verifying Your Email'
                : status === 'success'
                ? 'Email Verified!'
                : 'Verification Failed'}
            </Typography>

            {/* Content */}
            {!token ? (
              <Stack spacing={3}>
                <Alert severity="info">No verification token found.</Alert>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Please use the link sent to your email address to verify your account.
                </Typography>
                <Button 
                  variant="contained" 
                  onClick={() => router.push(paths.auth.jwt.login)}
                >
                  Return to Login
                </Button>
              </Stack>
            ) : status === 'verifying' ? (
              <Stack spacing={2} alignItems="center">
                <CircularProgress />
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Please wait while we verify your email address...
                </Typography>
              </Stack>
            ) : status === 'success' ? (
              <Stack spacing={3}>
                <Alert severity="success">
                  {message || 'Your email has been successfully verified! You can now log in to your account.'}
                </Alert>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Please proceed to login to access your account.
                </Typography>
                <Button 
                  variant="contained" 
                  onClick={() => router.push(paths.auth.jwt.login)}
                >
                  Go to Login
                </Button>
              </Stack>
            ) : (
              <Stack spacing={3}>
                <Alert severity="error">
                  {message || 'Verification failed. Please try again or request a new verification link.'}
                </Alert>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  If the problem persists, please contact support.
                </Typography>
                <Stack direction="row" spacing={2} justifyContent="center">
                  <Button 
                    variant="contained" 
                    onClick={() => verifyEmail()}
                  >
                    Try Again
                  </Button>
                  <Button 
                    variant="outlined" 
                    onClick={() => router.push(paths.auth.jwt.login)}
                  >
                    Back to Login
                  </Button>
                </Stack>
              </Stack>
            )}
          </Stack>
        </Card>
      </Container>
    </Box>
  );
} 