"use client";

import type { ReactElement } from "react";
import { Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/lib/auth/auth-context";

function CallbackContent(): ReactElement {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { refreshSession } = useAuth();

  useEffect(() => {
    async function handleCallback(): Promise<void> {
      // Check for OAuth errors
      const error = searchParams.get("error");
      if (error) {
        console.error("OAuth error:", error, searchParams.get("error_description"));
        router.push(`/login?error=${error}`);
        return;
      }

      // Refresh the session to load the authenticated user
      try {
        await refreshSession();
        router.push("/tasks");
      } catch (_error) {
        console.error("Session refresh failed:", _error);
        router.push("/login?error=session_failed");
      }
    }

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

  return (
    <div className="flex min-h-screen flex-col items-center justify-center p-8">
      <div className="text-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mx-auto mb-4"></div>
        <h1 className="text-2xl font-semibold mb-2">Completing authentication...</h1>
        <p className="text-gray-600">You will be redirected shortly.</p>
      </div>
    </div>
  );
}

export default function CallbackPage(): ReactElement {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen flex-col items-center justify-center p-8">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mx-auto mb-4"></div>
            <h1 className="text-2xl font-semibold mb-2">Loading...</h1>
          </div>
        </div>
      }
    >
      <CallbackContent />
    </Suspense>
  );
}
