"use client";

import { Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";

function OAuthCompleteContent() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const { update } = useSession();

    useEffect(() => {
        async function completeOAuth() {
            const status = searchParams.get("status");
            const provider = searchParams.get("provider");

            // Force NextAuth to refresh the session token
            await update();

            if (status === "connected") {
                router.replace(`/tasks?calendar=${provider}_connected&openSettings=calendars`);
            } else {
                const message = searchParams.get("message") || "connection_failed";
                router.replace(`/tasks?error=${message}`);
            }
        }

        completeOAuth();
    }, [router, searchParams, update]);

    return (
        <div style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "100vh",
            fontFamily: "Inter, sans-serif",
        }}>
            <div style={{ textAlign: "center" }}>
                <div style={{
                    width: "24px",
                    height: "24px",
                    border: "3px solid rgba(0,0,0,0.1)",
                    borderTopColor: "#3b82f6",
                    borderRadius: "50%",
                    animation: "spin 0.8s linear infinite",
                    margin: "0 auto 16px",
                }} />
                <p style={{ color: "#6b7280" }}>Completing connection...</p>
                <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            </div>
        </div>
    );
}

export default function OAuthCompletePage() {
    return (
        <Suspense fallback={
            <div style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "100vh",
                fontFamily: "Inter, sans-serif",
            }}>
                <p style={{ color: "#6b7280" }}>Loading...</p>
            </div>
        }>
            <OAuthCompleteContent />
        </Suspense>
    );
}
