import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  CircularProgress,
  Alert,
  Button
} from '@mui/material';
import { useVerifyCode } from '../hooks/apiHooks';
import { useAuth } from '../hooks/reduxHooks';

const VerifyPage = () => {
  const [verificationStatus, setVerificationStatus] = useState('pending'); // pending, success, error
  const [errorMessage, setErrorMessage] = useState('');
  const location = useLocation();
  const navigate = useNavigate();
  const { isAuthenticated } = useAuth();
  const verifyCode = useVerifyCode();

  // If already authenticated, redirect to home
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/');
    }
  }, [isAuthenticated, navigate]);

  // Extract code and email from URL params
  useEffect(() => {
    if(location.search, verifyCode, navigate){
        const queryParams = new URLSearchParams(location.search);
        const code = queryParams.get('code');
        const email = queryParams.get('email');
    
        // attempt verification
        if (code && email) {
          setVerificationStatus('verifying');
          verifyCode.mutate(
            { email, code },
            {
              onSuccess: () => {
                setVerificationStatus('success');
                // Redirect to home after successful verification
                setTimeout(() => {
                  navigate('/');
                }, 2000);
              },
              onError: (error) => {
                setVerificationStatus('error');
                setErrorMessage(error.message || 'Verification failed. Please try again.');
              }
            }
          );
        } else {
          setVerificationStatus('error');
          setErrorMessage('Missing verification code or email. Please check your link.');
        }
    }
  }, []);

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '100vh',
        bgcolor: (theme) => theme.palette.mode === 'dark' ? 'background.default' : 'grey.100',
        p: 3
      }}
    >
      <Paper
        elevation={3}
        sx={{
          width: '100%',
          maxWidth: 400,
          p: 4,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}
      >
        <Typography variant="h5" gutterBottom>
          Account Verification
        </Typography>

        {verificationStatus === 'pending' || verificationStatus === 'verifying' ? (
          <Box sx={{ textAlign: 'center', py: 3 }}>
            <CircularProgress size={48} sx={{ mb: 2 }} />
            <Typography>
              Verifying your account...
            </Typography>
          </Box>
        ) : verificationStatus === 'success' ? (
          <Alert severity="success" sx={{ width: '100%', mb: 2 }}>
            Your account has been verified successfully! Redirecting to home page...
          </Alert>
        ) : (
          <>
            <Alert severity="error" sx={{ width: '100%', mb: 2 }}>
              {errorMessage}
            </Alert>
            <Button
              variant="contained"
              onClick={() => navigate('/auth/login')}
              sx={{ mt: 2 }}
            >
              Back to Login
            </Button>
          </>
        )}
      </Paper>
    </Box>
  );
};

export default VerifyPage;