"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAppDispatch } from "@/app/hooks/useDispatch";
import { handleGoogleOAuthCallback } from "@/app/redux/services/auth/authServices";
import { fetchUserWallets } from "@/app/redux/services/main/campaigns/mycampaign";
import Swal from "sweetalert2";

interface AuthResponse {
  status: number;
  jwt: string;
  user_id: number;
  name: string;
  date_of_birth?: string;
  christian_name?: string;
  sur_name?: string;
  person_to_contact?: string;
  phone?: string;
  organization?: string;
  email: string;
  username: string;
  community?: string;
  avtar_text?: string;
  photo?: string;
  accountStatus?: string;
  role?: number;
  promo_code?: string;
  stripe_coupon_id?: string;
  stripe_customer_id?: string;
  promo_code_assigned?: boolean;
  wallets?: Array<{
    id: number;
    balance: number;
    notes: string;
    expiry_date: Date;
    created_at: Date;
    updated_at: Date;
  }>;
  message: string;
}

function AuthCallbackContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useAppDispatch();
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const handleCallback = async () => {
      try {
        // Get the data from query params (base64 encoded)
        const dataParam = searchParams.get("data");

        if (!dataParam) {
          // Check if it's an error redirect
          const errorMessage = searchParams.get("message");
          if (errorMessage) {
            setError(decodeURIComponent(errorMessage));
            setLoading(false);
            Swal.fire({
              icon: "error",
              title: "Authentication Error",
              text: decodeURIComponent(errorMessage),
              confirmButtonText: "OK",
            }).then(() => {
              router.push("/login");
            });
            return;
          }
          throw new Error("No authentication data received");
        }

        // Decode the base64 response
        // In browser, we need to use atob instead of Buffer
        const decodedData = atob(decodeURIComponent(dataParam));
        const authResponse: AuthResponse = JSON.parse(decodedData);

        if (authResponse.status === 200 && authResponse.jwt) {
          // Format response to match normal login structure
          // Pass the entire authResponse as data (same structure as loginUser)
          await dispatch(
            handleGoogleOAuthCallback({
              jwt: authResponse.jwt,
              user_id: authResponse.user_id,
              name: authResponse.name,
              date_of_birth: authResponse.date_of_birth,
              christian_name: authResponse.christian_name,
              sur_name: authResponse.sur_name,
              person_to_contact: authResponse.person_to_contact,
              phone: authResponse.phone,
              organization: authResponse.organization,
              email: authResponse.email,
              username: authResponse.username,
              community: authResponse.community,
              avtar_text: authResponse.avtar_text,
              photo: authResponse.photo,
              accountStatus: authResponse.accountStatus,
              role: authResponse.role,
              promo_code: authResponse.promo_code,
              stripe_coupon_id: authResponse.stripe_coupon_id,
              stripe_customer_id: authResponse.stripe_customer_id,
              promo_code_assigned: authResponse.promo_code_assigned,
              wallets: authResponse.wallets,
            })
          ).unwrap();

          // Fetch wallets
          try {
            await dispatch(fetchUserWallets()).unwrap();
          } catch (walletError) {
            console.error("Error fetching wallets:", walletError);
          }

          // Show success message
          Swal.fire({
            title: "Bienvenue",
            icon: "success",
            showConfirmButton: false,
            timer: 1500,
          }).then(() => {
            router.push("/home");
          });
        } else {
          setError(authResponse.message || "Authentication failed");
          setLoading(false);
          Swal.fire({
            icon: "error",
            title: "Authentication Failed",
            text: authResponse.message || "Authentication failed",
            confirmButtonText: "OK",
          }).then(() => {
            router.push("/login");
          });
        }
      } catch (err: any) {
        console.error("Auth callback error:", err);
        setError("Failed to process authentication. Please try again.");
        setLoading(false);
        Swal.fire({
          icon: "error",
          title: "Error",
          text: "Failed to process authentication. Please try again.",
          confirmButtonText: "OK",
        }).then(() => {
          router.push("/login");
        });
      }
    };

    handleCallback();
  }, [searchParams, router, dispatch]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Completing sign in...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center max-w-md p-6 bg-red-50 border border-red-200 rounded-lg">
          <h2 className="text-xl font-semibold text-red-800 mb-2">
            Authentication Error
          </h2>
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={() => router.push("/login")}
            className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
          >
            Back to Login
          </button>
        </div>
      </div>
    );
  }

  return null;
}

export default function AuthCallbackPage() {
  return (
    <Suspense
      fallback={
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">Loading...</p>
          </div>
        </div>
      }
    >
      <AuthCallbackContent />
    </Suspense>
  );
}
