"use client";

import { useRef, useEffect, useCallback, useState } from "react";
import { useSocialSignin } from "@/features/auth/hooks/useAuth";
import config from "@/utils/config";
import { GoogleLogin, useGoogleLogin } from "@react-oauth/google";

declare global {
  interface Window {
    google?: {
      accounts: {
        id: {
          initialize: (config: {
            client_id: string;
            callback: (response: { credential: string }) => void;
          }) => void;
          renderButton: (
            parent: HTMLElement,
            options: { type?: "icon" | "standard"; size?: "large" | "medium"; theme?: "outline" | "filled_blue" | "filled_black" }
          ) => void;
        };
      };
    };
    FB?: {
      init: (opts: { appId: string; cookie?: boolean; xfbml?: boolean; version: string }) => void;
      login: (
        callback: (res: { status?: string; authResponse?: { accessToken: string } }) => void,
        opts?: { scope?: string }
      ) => void;
    };
    fbAsyncInit?: () => void;
    AppleID?: {
      auth: {
        init: (config: { clientId: string; scope: string; redirectURI: string; usePopup: boolean }) => void;
        signIn: () => Promise<{
          authorization?: { id_token?: string; identity_token?: string };
        }>;
      };
    };
  }
}

const FACEBOOK_SDK_SRC = config.ENV_VARS.FACEBOOK_SDK_SRC;

interface SocialAuthButtonsProps {
  onError?: (error: string) => void;
  /** Called when social sign-in/sign-up succeeds (e.g. close modal) */
  onSuccess?: () => void;
}

const debugLog = (...args: unknown[]) => {
  console.log("[SocialAuthButtons]", ...args);
};

function getErrorMessage(err: unknown): string {
  if (err && typeof err === "object" && "response" in err) {
    const r = (err as { response?: { data?: { message?: string } } }).response;
    if (r?.data?.message) return r.data.message;
  }
  if (err instanceof Error) return err.message;
  return "Sign-in failed. Please try again.";
}

export default function SocialAuthButtons({ onError, onSuccess }: SocialAuthButtonsProps) {
  const socialSigninMutation = useSocialSignin();
  const facebookAppId = config.ENV_VARS.FACEBOOK_CLIENT_ID;
  const appleClientId = config.ENV_VARS.APPLE_CLIENT_ID;
  const appleRedirectUri =
    config.ENV_VARS.APPLE_REDIRECT_URI ||
    (typeof window !== "undefined" ? window.location.origin : "");
  const onErrorRef = useRef(onError);
  const onSuccessRef = useRef(onSuccess);
  useEffect(() => {
    onErrorRef.current = onError;
  }, [onError]);
  useEffect(() => {
    onSuccessRef.current = onSuccess;
  }, [onSuccess]);

  type SocialProvider = "GOOGLE" | "FACEBOOK" | "APPLE";

  const handleSocialToken = useCallback(
    async (provider: SocialProvider, token: string, client: string) => {
      if (!token?.trim()) {
        debugLog("handleSocialToken:missing-token", { provider });
        onErrorRef.current?.("No token received from provider.");
        return;
      }

      try {
        await socialSigninMutation.mutateAsync({
          provider,
          token: token.trim(), // ← JWT goes here
          client,
        });
        onSuccessRef.current?.();
      } catch (err) {
        onErrorRef.current?.(getErrorMessage(err));
      }
    },
    [socialSigninMutation]
  );

  const login = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      try {
        // tokenResponse contains access_token
        const accessToken = tokenResponse.access_token;

        if (!accessToken) {
          onErrorRef.current?.("No access token received from Google");
          return;
        }

        await handleSocialToken("GOOGLE", accessToken, "web");
      } catch (err) {
        onErrorRef.current?.("Google login failed");
      }
    },
    onError: () => {
      onErrorRef.current?.("Google sign-in failed. Please try again.");
    },
  });

  // Load Facebook SDK and init
  useEffect(() => {
    if (!facebookAppId || typeof window === "undefined") return;
    const initFB = () => {
      window.FB?.init({
        appId: facebookAppId,
        cookie: true,
        xfbml: true,
        version: "v18.0",
      });
    };
    const existing = document.getElementById("facebook-jssdk");
    if (existing) {
      if (window.FB) initFB();
      return;
    }
    window.fbAsyncInit = initFB;
    const script = document.createElement("script");
    script.id = "facebook-jssdk";
    script.src = FACEBOOK_SDK_SRC;
    script.async = true;
    script.defer = true;
    script.crossOrigin = "anonymous";
    document.head.appendChild(script);
  }, [facebookAppId]);

  // Load Apple Sign In script and init


  const handleFacebook = useCallback(() => {
    debugLog("facebook:click", { hasAppId: Boolean(facebookAppId), hasSDK: Boolean(window.FB) });
    if (!facebookAppId) {
      onErrorRef.current?.("Facebook sign-in is not configured. Set NEXT_PUBLIC_FACEBOOK_CLIENT_ID.");
      return;
    }
    if (!window.FB) {
      onErrorRef.current?.("Facebook SDK is still loading. Please try again in a moment.");
      return;
    }
    window.FB.login(
      (response) => {
        debugLog("facebook:callback", {
          status: response?.status,
          hasToken: Boolean(response?.authResponse?.accessToken),
        });
        if (response.status === "connected" && response.authResponse?.accessToken) {
          handleSocialToken("FACEBOOK", response.authResponse.accessToken, 'web');
        } else {
          onErrorRef.current?.(
            response.status === "unknown" ? "Facebook sign-in was cancelled." : "Facebook sign-in failed."
          );
        }
      },
      { scope: "email,public_profile" }
    );
  }, [facebookAppId, handleSocialToken]);

  const handleApple = useCallback(() => {


    if (!appleClientId || !appleRedirectUri) {

      onErrorRef.current?.(
        "Apple sign-in is not configured. Missing ENV values."
      );
      return;
    }

    if (!window.AppleID?.auth) {
      onErrorRef.current?.(
        "Apple Sign In is still loading. Please try again in a moment."
      );
      return;
    }

    try {


      window.AppleID.auth
        .signIn()
        .then((data) => {
          console.log("✅ APPLE RESPONSE FULL:", data);
          console.log("🍎 TOKEN CHECK:", data?.authorization)
          const token =
            data?.authorization?.id_token ??
            data?.authorization?.identity_token ??
            "";



          if (token) {
            handleSocialToken("APPLE", token, "web");
          } else {
            onErrorRef.current?.(
              "Apple did not return an identity token."
            );
          }
        })
        .catch((err) => {


          if (err?.error === "invalid_request") {
            console.error(" INVALID REQUEST → Likely config mismatch", {
              clientId: appleClientId,
              redirectUri: appleRedirectUri,
            });
          }

          if (
            err?.error === "popup_closed_by_user" ||
            err?.error === "user_canceled"
          ) {
            onErrorRef.current?.("Apple sign-in was cancelled.");
          } else {
            onErrorRef.current?.(getErrorMessage(err));
          }
        });
    } catch {
      return
    }
  }, [appleClientId, appleRedirectUri, handleSocialToken]);

  // console.log('isGoogleReady',isGoogleReady);
  return (
    <>

      <div className="d-flex justify-content-center gap-2 otherLoginOptions align-items-center">
        {/* Facebook */}
        <span
          role="button"
          className="login-icon-button border text-center rounded-circle"
          onClick={handleFacebook}
          aria-label="Continue with Facebook"
        // aria-disabled={isLoading}
        >
          <svg className="iconSize-20" viewBox="0 0 12 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M7.79563 24V13.0703H11.3496L11.8779 8.79094H7.79563V6.06518C7.79563 4.83032 8.12725 3.98485 9.83547 3.98485H12V0.169586C10.9468 0.0524886 9.88823 -0.00405133 8.82905 0.00022559C5.68766 0.00022559 3.53085 1.98987 3.53085 5.64245V8.78294H0V13.0623H3.53856V24H7.79563Z"
              fill="#4092FF"
            />
          </svg>
        </span>

        {/* Google — custom icon always visible; GSI button overlaid (invisible) so click opens popup */}

        <div className="position-relative d-inline-block"
        style={{ width: 40, height: 40 }}>
        <button
         onClick={() => login()}
        //  disabled={isLoading}
          type="button"
          className="login-icon-button border rounded-circle overflow-hidden bg-white w-100 h-100"
        
        >

          <span className="d-flex align-items-center justify-content-center w-100 h-100" aria-hidden="true">
            <svg className="iconSize-20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M5.23832 14.2839L4.41557 17.3554L1.40844 17.419C0.509752 15.7521 0 13.845 0 11.8184C0 9.85863 0.476605 8.01056 1.32142 6.3833H1.32207L3.99925 6.87412L5.17202 9.53525C4.92657 10.2508 4.79278 11.019 4.79278 11.8184C4.79287 12.6859 4.95002 13.5171 5.23832 14.2839Z" fill="#FBBB00" />
              <path d="M23.43 9.61035C23.5657 10.3253 23.6365 11.0636 23.6365 11.8181C23.6365 12.6642 23.5475 13.4896 23.3781 14.2857C22.8028 16.9948 21.2995 19.3604 19.217 21.0344L15.8443 20.8617L15.3671 17.8824C16.7489 17.0721 17.8288 15.8039 18.3976 14.2857H12.0781V9.61035H23.43Z" fill="#518EF8" />
              <path d="M19.2162 21.0337C17.1916 22.6622 14.6188 23.6363 11.8182 23.6363C7.31754 23.6363 3.40457 21.1207 1.40845 17.4187L5.23832 14.2837C6.23636 16.9473 8.80584 18.8434 11.8182 18.8434C13.113 18.8434 14.326 18.4934 15.3669 17.8824L19.2162 21.0337Z" fill="#28B446" />
              <path d="M19.3618 2.72077L15.5332 5.85517C14.456 5.18181 13.1826 4.79283 11.8183 4.79283C8.73777 4.79283 6.12022 6.77593 5.17218 9.53506L1.32218 6.38311C3.28843 2.59091 7.25075 0 11.8183 0C14.6858 0 17.315 1.02144 19.3618 2.72077Z" fill="#F14336" />
            </svg>
          </span>
        </button>
        <div
          className="position-absolute  top-0 start-0 w-100 h-100"
          style={{ opacity: 0.01 }}
        >
          <GoogleLogin
            onSuccess={(credentialResponse) => {
              const idToken = credentialResponse.credential;

              if (!idToken) {
                onErrorRef.current?.("Google did not return a token");
                return;
              }

              // console.log("GOOGLE ID TOKEN SEGMENTS:", idToken.split(".").length); // must be 3
              handleSocialToken("GOOGLE", idToken, 'web');
            }}
            onError={() => {
              onErrorRef.current?.("Google sign-in failed. Please try again.");
            }}
            useOneTap={false}
            theme="outline"
            size="large"
          />
        </div>

      </div>



        {/* Apple */}
        <span
          role="button"
          className="login-icon-button border text-center rounded-circle"
          style={{ position: "relative", zIndex: 2 }}
          onClick={handleApple}
          aria-label="Continue with Apple"
        // aria-disabled={isLoading}
        >
          <svg className="iconSize-20 fill-black" viewBox="0 0 22 26" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M5.23494 25.5131C4.72232 25.1721 4.268 24.7507 3.88944 24.2651C3.47302 23.764 3.08719 23.2381 2.73406 22.6905C1.90538 21.4765 1.2555 20.1497 0.804375 18.7507C0.262437 17.1257 0 15.5681 0 14.0447C0 12.3433 0.368063 10.8581 1.08794 9.61009C1.62157 8.63463 2.40615 7.81948 3.3605 7.24896C4.28537 6.6745 5.34807 6.36013 6.43662 6.33896C6.81769 6.33896 7.228 6.39421 7.6635 6.49984C7.97631 6.5884 8.35737 6.72815 8.82294 6.90202C9.41525 7.13034 9.74106 7.27009 9.85156 7.30421C10.1985 7.43096 10.4902 7.48621 10.7193 7.48621C10.8932 7.48621 11.1386 7.43096 11.4172 7.34646C11.5741 7.29121 11.8698 7.19371 12.2931 7.01252C12.7124 6.85977 13.0422 6.72896 13.3047 6.63146C13.7069 6.51284 14.0961 6.40315 14.443 6.3479C14.8543 6.28306 15.2717 6.26588 15.6869 6.29671C16.4065 6.34374 17.1153 6.49622 17.7905 6.74927C18.8947 7.19371 19.7876 7.88759 20.4522 8.87396C20.1713 9.0471 19.9077 9.24681 19.6649 9.47034C19.1365 9.93881 18.6864 10.4888 18.3316 11.0994C17.8679 11.9339 17.6275 12.8739 17.6337 13.8286C17.6507 15.001 17.9514 16.0337 18.5437 16.9266C18.9791 17.5884 19.5451 18.1544 20.2069 18.5898C20.5457 18.8181 20.8374 18.975 21.1169 19.0806C20.9861 19.4868 20.8463 19.8801 20.6814 20.2701C20.3073 21.1447 19.8539 21.9831 19.3269 22.775C18.8573 23.4567 18.4892 23.9645 18.2097 24.3025C17.7742 24.8185 17.355 25.2125 16.9317 25.4871C16.4661 25.7959 15.9161 25.9608 15.3571 25.9608C14.9785 25.9754 14.6 25.9296 14.2358 25.8251C13.923 25.7195 13.6134 25.605 13.3087 25.4741C12.992 25.3287 12.6654 25.2057 12.3313 25.1061C11.5056 24.894 10.6398 24.8926 9.81337 25.102C9.47456 25.1995 9.14875 25.3133 8.827 25.453C8.37444 25.6431 8.07381 25.7707 7.89994 25.8251C7.553 25.9267 7.19306 25.9901 6.82906 26.0112C6.266 26.0112 5.74112 25.8503 5.22112 25.5245L5.23494 25.5131ZM12.6612 5.51346C11.9251 5.88152 11.2222 6.03834 10.5243 5.98715C10.4146 5.28434 10.5243 4.56527 10.816 3.77796C11.0643 3.11095 11.4313 2.49436 11.8991 1.95796C12.3931 1.39329 12.9925 0.930454 13.6638 0.595398C14.3788 0.227336 15.0605 0.0282734 15.7121 -0.000976562C15.7966 0.735148 15.7121 1.45909 15.4416 2.24152C15.1912 2.93319 14.8249 3.57722 14.3585 4.14602C13.8824 4.71147 13.2982 5.1761 12.6401 5.51265L12.6612 5.51346Z" />
          </svg>
        </span>


      </div>

    </>
  );
}
