"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { useAuth } from "@/lib/auth-context";

export default function CallbackPage() {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const { login, user } = useAuth();

  useEffect(() => {
    async function handleCallback() {
      try {
        // Get the code from the URL query parameters
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');

        if (!code) {
          throw new Error('No authorization code found in the URL');
        }

        // Use the auth context to login
        await login(code);

        // Check if there's a stored callbackUrl
        const callbackUrl = sessionStorage.getItem('callbackUrl');

        // Clear the stored callbackUrl
        sessionStorage.removeItem('callbackUrl');

        // Redirect based on role and callbackUrl
        if (callbackUrl) {
          // For admin routes, check if user has admin role
          if (callbackUrl.startsWith('/admin') && user?.role !== 'ADMIN') {
            router.push('/dashboard');
          } else {
            router.push(callbackUrl);
          }
        } else {
          // Default redirects if no callbackUrl
          if (user && user.role === 'ADMIN') {
            router.push('/admin');
          } else {
            router.push('/dashboard');
          }
        }
      } catch (err) {
        console.error("Authentication error:", err);
        setError("Une erreur est survenue lors de l'authentification. Veuillez réessayer.");
      }
    }

    handleCallback();
  }, [router]);

  if (error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center p-4 text-center">
        <div className="mb-4 text-red-500">{error}</div>
        <a
          href="/auth/login"
          className="text-primary hover:underline"
        >
          Retour à la page de connexion
        </a>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center p-4 text-center">
      <Loader2 className="mb-4 h-8 w-8 animate-spin text-primary" />
      <h1 className="mb-2 text-xl font-semibold">Authentification en cours...</h1>
      <p className="text-muted-foreground">Vous allez être redirigé vers l'application.</p>
    </div>
  );
}
