"use client";
import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

export default function GoogleLoginCallback() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [isProcessing, setIsProcessing] = useState(true);
  const [error, setError] = useState("");

  const handleGoogleAuth = useCallback(
    async (user: any) => {
      try {
        setIsProcessing(true);
        console.log("Google user data:", user);
        console.log("Google user keys:", Object.keys(user));
       
        const source = localStorage.getItem("google_auth_source") || "signup";
        const isLogin = source === "login";

        localStorage.removeItem("google_auth_source");

        const endpoint = isLogin ? "/api/auth/google-login" : "/api/auth/google-auth";
        console.log("Using endpoint:", endpoint, "Is login:", isLogin);
        
        // Extract google_id from available fields
        const google_id = user.id || user.sub || user.email;
        
        const payload = {
          email: user.email,
          name: user.name,
          google_id: google_id,
          image: user.image,
          provider: "google",
          action: isLogin ? "login" : "signup",
        };
        
        console.log("Sending payload:", payload);

        const response = await fetch(endpoint, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });

        console.log("Response status:", response.status);
        console.log("Response ok:", response.ok);

        const data = await response.json();
        console.log("Response data:", data);

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status} - ${data.message || 'Unknown error'}`);
        }

        if (data.success) {
          // Tokens are now set server-side in HTTP-only cookies
          localStorage.setItem("user", JSON.stringify(data.user || user));

          if (endpoint !== "/api/auth/google-login") {
            router.push("/onboarding/step2");
          } else {
            const storedRedirect =
              typeof window !== "undefined"
                ? localStorage.getItem("google_auth_redirect")
                : null;

            if (storedRedirect) {
              if (typeof window !== "undefined") {
                localStorage.removeItem("google_auth_redirect");
              }
              router.push(storedRedirect);
            } else {
              router.push("/category");
            }
          }
        } else {
          console.error("Authentication failed:", data.message);
          setError(data.message || "Authentication failed. Please try again.");
          setTimeout(() => router.push("/auth/signup"), 3000);
        }
      } catch (err: any) {
        console.error("Google authentication error:", err);
        console.error("Error message:", err.message);
        console.error("Error stack:", err.stack);
        
        setError(
          `Error: ${err.message || 'Authentication failed. Please try again.'}`,
        );
        
        // Don't redirect automatically on error, let user see the error
        setTimeout(() => router.push("/auth/signup"), 5000);
      } finally {
        setIsProcessing(false);
      }
    },
    [router],
  );

  useEffect(() => {
    if (status === "loading") return;

    if (status === "unauthenticated") {
      console.log("User not authenticated, redirecting to signup");
      router.push("/auth/signup");
      return;
    }

    if (session?.user && status === "authenticated") {
      console.log("User authenticated, processing Google auth");
      handleGoogleAuth(session.user);
    }
  }, [session, status, router, handleGoogleAuth]);

  if (error) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gray-50">
        <div className="w-full max-w-md text-center">
          <div className="rounded-lg bg-white p-8 shadow-md">
            <div className="mb-4 text-xl text-red-500"></div>
            <h2 className="mb-4 text-xl font-semibold text-gray-900">
              Authentication Status
            </h2>
            <p className="mb-4 text-sm text-gray-600">{error}</p>
            <div className="mt-4">
              <button
                onClick={() => router.push("/dashboard")}
                className="mr-2 rounded bg-blue-500 px-4 py-2 text-white"
              >
                Go to Dashboard
              </button>
              <button
                onClick={() => router.push("/auth/signup")}
                className="rounded bg-gray-500 px-4 py-2 text-white"
              >
                Back to Signup
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50">
      <div className="w-full max-w-md text-center">
        <div className="rounded-lg bg-white p-8 shadow-md">
          <div className="mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-gray-900"></div>
          <h2 className="mb-4 text-xl font-semibold text-gray-900">
            Authenticating with Google
          </h2>
          <p className="text-gray-600">
            Please wait while we complete your Google authentication...
          </p>
        </div>
      </div>
    </div>
  );
}
