// app/auth/callback/page.tsx
'use client';

import { Suspense } from 'react'; // <-- Import Suspense
import { useEffect, useState, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2, Chrome, Facebook } from 'lucide-react';
import toast from 'react-hot-toast';

// Create a separate component that uses useSearchParams
function AuthCallbackContent() {
  const router = useRouter();
  const searchParams = useSearchParams(); // <-- Now safely used inside Suspense
  const [status, setStatus] = useState('processing');

  const handleError = useCallback((error: string, provider: string | null) => {
    let errorMessage = 'Authentication failed';
    
    const errorMap: Record<string, string> = {
      // Google errors
      'google_auth_failed': 'Google authentication failed. Please try again.',
      'google_access_denied': 'You denied Google login. Please try again.',
      
      // Facebook errors  
      'facebook_auth_failed': 'Facebook authentication failed. Please try again.',
      'facebook_access_denied': 'You denied Facebook login. Please try again.',
      'email_required': 'Facebook did not provide your email. Please use another login method.',
      'failed_to_get_token': 'Failed to get access token from Facebook. Please try again.',
      'failed_to_get_user_info': 'Failed to get your information from Facebook. Please try again.',
      
      // Common errors
      'no_code': 'No authorization code received. Please try again.',
      'invalid_user_info': 'Could not retrieve your user information. Please try again.',
      'internal_server_error': 'An internal server error occurred. Please try again later.'
    };

    errorMessage = errorMap[error] || decodeURIComponent(error) || errorMessage;
    toast.error(errorMessage); // Removed the provider from toast as it's already in the message
    
    // Clear cookies
    document.cookie = 'user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
    document.cookie = 'accessToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
    document.cookie = 'refreshToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
    
    setTimeout(() => router.push('/login'), 500);
  }, [router]);

  useEffect(() => {
    const success = searchParams.get('success');
    const error = searchParams.get('error');
    const provider = searchParams.get('provider');

    const processAuth = async () => {
      if (success === 'true') {
        setStatus('success');
        
        const providerName = provider 
          ? provider.charAt(0).toUpperCase() + provider.slice(1) 
          : '';
        
        toast.success(`${providerName} login successful!`.trim());
        
        setTimeout(() => router.push('/dashboard'), 500);
        
      } else if (error) {
        setStatus('error');
        handleError(error, provider);
      }
    };

    processAuth();
  }, [router, searchParams, handleError]);

  const getProviderIcon = () => {
    const provider = searchParams.get('provider');
    switch (provider) {
      case 'google':
        return <Chrome className="h-12 w-12 text-blue-500 mx-auto mb-4" />;
      case 'facebook':
        return <Facebook className="h-12 w-12 text-[#1877F2] mx-auto mb-4" />;
      default:
        return <Loader2 className="h-12 w-12 animate-spin text-blue-600 mx-auto mb-4" />;
    }
  };

  const getProviderName = () => {
    const provider = searchParams.get('provider');
    return provider 
      ? provider.charAt(0).toUpperCase() + provider.slice(1) 
      : '';
  };

  return (
    <div className="text-center max-w-md px-4 py-8 bg-white rounded-2xl shadow-lg">
      {status === 'processing' && (
        <>
          {getProviderIcon()}
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            Completing authentication...
          </h2>
          <p className="text-gray-600">
            Please wait while we sign you in
          </p>
          {getProviderName() && (
            <div className="mt-4 inline-flex items-center px-3 py-1 bg-gray-100 rounded-full">
              <span className="text-sm text-gray-700">
                Signing in with {getProviderName()}
              </span>
            </div>
          )}
        </>
      )}
      
      {status === 'success' && (
        <>
          <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="h-8 w-8 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            Login Successful!
          </h2>
          <p className="text-gray-600">
            Redirecting you to dashboard...
          </p>
        </>
      )}
      
      {status === 'error' && (
        <>
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="h-8 w-8 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            Authentication Failed
          </h2>
          <p className="text-gray-600">
            Redirecting you to login page...
          </p>
        </>
      )}
    </div>
  );
}

// Main page component with Suspense
export default function AuthCallbackPage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <Suspense fallback={
        <div className="text-center max-w-md px-4 py-8 bg-white rounded-2xl shadow-lg">
          <Loader2 className="h-12 w-12 animate-spin text-blue-600 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            Loading...
          </h2>
          <p className="text-gray-600">
            Preparing authentication callback
          </p>
        </div>
      }>
        <AuthCallbackContent />
      </Suspense>
    </div>
  );
}