import React, { useEffect, useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import API_BASE_URL from '../config/api';
import './VerifyEmail.css';

const VerifyEmail = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [status, setStatus] = useState('verifying');
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Auto-close after 10 seconds from page open
    const closeTimer = setTimeout(() => {
      navigate('/');
    }, 10000);

    const verifyEmail = async () => {
      const token = searchParams.get('token');

      if (!token) {
        setStatus('error');
        setMessage('No verification token provided');
        return;
      }

      try {
        const response = await axios.get(`${API_BASE_URL}/auth/verify-email?token=${token}`);
        setStatus('success');
        setMessage('Email verified successfully!');
        // Redirect to success page after verification
        navigate('/verify-email-success');
      } catch (error) {
        setStatus('error');
        setMessage(error.response?.data?.message || 'Verification failed');
      }
    };

    verifyEmail();

    // Cleanup timer on unmount
    return () => clearTimeout(closeTimer);
  }, [searchParams, navigate]);

  return (
    <div className="verify-email-container">
      <div className="verify-email-card">
        {status === 'verifying' && (
          <div className="verifying">
            <div className="spinner"></div>
            <h2>Verifying your email...</h2>
          </div>
        )}

        {status === 'success' && (
          <div className="success">
            <div className="success-icon">✓</div>
            <h2>Email Verified!</h2>
            <p>{message}</p>
            <p className="redirect-message">Redirecting to home page in 10 seconds...</p>
            <button
              className="close-btn"
              onClick={() => navigate('/')}
            >
              Go to Home Now
            </button>
          </div>
        )}

        {status === 'error' && (
          <div className="error">
            <div className="error-icon">✕</div>
            <h2>Verification Failed</h2>
            <p>{message}</p>
            <button
              className="retry-btn"
              onClick={() => navigate('/login')}
            >
              Back to Login
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default VerifyEmail;
