import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import Spinner from "@/components/Spinner";

interface State {
  loading: boolean;
  errorMessage: string;
}

const AuthCallback = () => {
  const [searchParams] = useSearchParams();
  const [state, setState] = useState<State>({
    loading: true,
    errorMessage: "",
  });

  useEffect(() => {
    // Check for OAuth error response first (e.g., user denied access)
    const error = searchParams.get("error");
    const errorDescription = searchParams.get("error_description");
    const errorUri = searchParams.get("error_uri");

    if (error) {
      // OAuth provider returned an error
      let errorMessage = `OAuth error: ${error}`;
      if (errorDescription) {
        errorMessage += `\n${decodeURIComponent(errorDescription)}`;
      }
      if (errorUri) {
        errorMessage += `\nMore info: ${errorUri}`;
      }

      setState({
        loading: false,
        errorMessage,
      });
      return;
    }

    // Legacy OAuth callback for memos has been deprecated.
    // Clerk now handles all OAuth flows internally.
      setState({
        loading: false,
      errorMessage: "This OAuth callback endpoint is no longer used. Authentication is handled by Clerk.",
            });
  }, [searchParams, navigateTo]);

  return (
    <div className="p-4 py-24 w-full h-full flex justify-center items-center">
      {state.loading ? (
        <Spinner size="lg" />
      ) : (
        <div className="max-w-lg font-mono whitespace-pre-wrap opacity-80">{state.errorMessage}</div>
      )}
    </div>
  );
};

export default AuthCallback;
