"use client";

import { Suspense, useEffect, useRef } from "react";
import { Spin, Typography } from "antd";
import { useSearchParams } from "next/navigation";

import { useAuth } from "@/lib/hooks/use-auth";

const { Paragraph } = Typography;

function CallbackContent() {
  const { handleSSOCallback } = useAuth();
  const params = useSearchParams();
  const code = params?.get("code");
  const state = params?.get("state");
  const error = params?.get("error");
  const errorDescription = params?.get("error_description");
  const lastHandledKey = useRef<string | null>(null);

  useEffect(() => {
    const key = `${code ?? ""}|${state ?? ""}|${error ?? ""}|${errorDescription ?? ""}`;
    if (lastHandledKey.current === key) {
      return;
    }
    lastHandledKey.current = key;
    void handleSSOCallback({ code, state, error, errorDescription });
  }, [code, error, errorDescription, handleSSOCallback, state]);

  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
      <Spin size="large" />
      <Paragraph style={{ marginTop: 16 }}>Completing sign-in...</Paragraph>
    </div>
  );
}

export default function CallbackPage() {
  return (
    <Suspense
      fallback={
        <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
          <Spin size="large" />
          <Paragraph style={{ marginTop: 16 }}>Completing sign-in...</Paragraph>
        </div>
      }
    >
      <CallbackContent />
    </Suspense>
  );
}
