import React, { useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { CheckCircle, XCircle, Loader2, Mail, ShieldCheck } from 'lucide-react';
import apiClient from '../api/client';
import { deleteCookie } from '../utils/cookies';

type VerificationStatus = 'pending' | 'loading' | 'success' | 'error' | 'already_verified';

const VerifyEmail: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [status, setStatus] = useState<VerificationStatus>('pending');
  const [errorMessage, setErrorMessage] = useState('');

  const token = searchParams.get('token');

  const handleVerify = async () => {
    if (!token) {
      setStatus('error');
      setErrorMessage('No verification token provided');
      return;
    }

    setStatus('loading');

    try {
      const response = await apiClient.get(`/api/auth/emails/verify/${token}/`);

      // Immediately clear auth cookies to log out
      deleteCookie('access_token');
      deleteCookie('refresh_token');

      if (response.data.message === 'Email is already verified') {
        setStatus('already_verified');
      } else {
        setStatus('success');
      }
    } catch (err: any) {
      setStatus('error');
      setErrorMessage(err.response?.data?.detail || 'Failed to verify email');
    }
  };

  // If no token, show error immediately
  if (!token) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="max-w-md w-full bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8 text-center">
          <div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-6">
            <XCircle size={32} className="text-red-500" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            Invalid Link
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            No verification token was provided. Please check your email for the correct link.
          </p>
          <button
            onClick={() => navigate('/login')}
            className="w-full px-4 py-3 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors font-medium"
          >
            Go to Login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
      <div className="max-w-md w-full bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8 text-center">
        {status === 'pending' && (
          <>
            <div className="mx-auto w-16 h-16 bg-brand-100 dark:bg-brand-900/30 rounded-full flex items-center justify-center mb-6">
              <ShieldCheck size={32} className="text-brand-500" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Verify Your Email
            </h1>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              Click the button below to confirm your email address.
            </p>
            <button
              onClick={handleVerify}
              className="w-full px-4 py-3 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors font-medium"
            >
              Confirm Verification
            </button>
          </>
        )}

        {status === 'loading' && (
          <>
            <div className="mx-auto w-16 h-16 bg-brand-100 dark:bg-brand-900/30 rounded-full flex items-center justify-center mb-6">
              <Loader2 size={32} className="text-brand-500 animate-spin" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Verifying Your Email
            </h1>
            <p className="text-gray-500 dark:text-gray-400">
              Please wait while we verify your email address...
            </p>
          </>
        )}

        {status === 'success' && (
          <>
            <div className="mx-auto w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mb-6">
              <CheckCircle size={32} className="text-green-500" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Email Verified!
            </h1>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              Your email address has been successfully verified. You can now sign in to your account.
            </p>
            <button
              onClick={() => window.location.href = '/login'}
              className="w-full px-4 py-3 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors font-medium"
            >
              Go to Login
            </button>
          </>
        )}

        {status === 'already_verified' && (
          <>
            <div className="mx-auto w-16 h-16 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center mb-6">
              <Mail size={32} className="text-blue-500" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Already Verified
            </h1>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              This email address has already been verified. You can use it to sign in to your account.
            </p>
            <button
              onClick={() => navigate('/login')}
              className="w-full px-4 py-3 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors font-medium"
            >
              Go to Login
            </button>
          </>
        )}

        {status === 'error' && (
          <>
            <div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-6">
              <XCircle size={32} className="text-red-500" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Verification Failed
            </h1>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              {errorMessage || 'We were unable to verify your email address. The link may have expired or is invalid.'}
            </p>
            <div className="space-y-3">
              <button
                onClick={() => navigate('/login')}
                className="w-full px-4 py-3 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors font-medium"
              >
                Go to Login
              </button>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                If you need a new verification link, please sign in and request one from your profile settings.
              </p>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default VerifyEmail;
