'use client';

import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { oauthService } from '@/lib/services/auth';
import { Loader2, AlertCircle } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';

export default function OAuthCallbackPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [error, setError] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState(true);

  useEffect(() => {
    const handleCallback = async () => {
      const code = searchParams.get('code');
      const state = searchParams.get('state');
      const error = searchParams.get('error');
      const provider = searchParams.get('provider');

      // Check for OAuth error
      if (error) {
        setError(`OAuth error: ${error}`);
        setIsProcessing(false);
        return;
      }

      // Validate required parameters
      if (!code || !state || !provider) {
        setError('Invalid OAuth callback - missing required parameters');
        setIsProcessing(false);
        return;
      }

      // Validate provider
      if (provider !== 'google' && provider !== 'discord') {
        setError(`Unsupported OAuth provider: ${provider}`);
        setIsProcessing(false);
        return;
      }

      try {
        // Handle the OAuth callback
        const { redirectUrl } = await oauthService.handleOAuthCallback(
          provider as 'google' | 'discord',
          code,
          state
        );

        // Redirect to the intended destination
        router.push(redirectUrl || '/dashboard');
      } catch (err: any) {
        console.error('OAuth callback error:', err);
        const errorMessage =
          err.response?.data?.detail ||
          err.message ||
          'Failed to complete OAuth login';
        setError(errorMessage);
        setIsProcessing(false);
      }
    };

    handleCallback();
  }, [searchParams, router]);

  if (isProcessing) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-center space-y-4">
          <Loader2 className="h-12 w-12 animate-spin mx-auto text-primary" />
          <div>
            <h2 className="text-2xl font-semibold">Signing you in...</h2>
            <p className="text-muted-foreground mt-2">
              Please wait while we complete your authentication
            </p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background p-4">
        <div className="max-w-md w-full space-y-4">
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Authentication Failed</AlertTitle>
            <AlertDescription>{error}</AlertDescription>
          </Alert>
          <div className="flex gap-3">
            <Button
              onClick={() => router.push('/login')}
              variant="outline"
              className="flex-1"
            >
              Back to Login
            </Button>
            <Button
              onClick={() => window.location.reload()}
              className="flex-1"
            >
              Try Again
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return null;
}
