import React, { use, useEffect, useState } from "react";
import { AUTHEN_TYPES, DOMAIN_TYPE } from "@/lib/appConstant";
import { makeStyles } from "tss-react/mui";
import AppButton from "./button";
import { useTranslations } from "use-intl";
import StorageHelper from "@/lib/storeHelper";
import { STORAGE_KEYS } from "@/types/common";
import { useAppSelector } from "@/lib/redux/hooks";
import {
  getServicePath,
  getViewSettings,
} from "@/lib/redux/features/serviceAdmin";
import { useRouter, useSearchParams } from "next/navigation";
import { useMounted } from "@/hooks/useMounted";
import { showToast } from "@/components/toast/showToast";

const useStyles = makeStyles()((theme) => ({
  logo: {
    marginRight: "10px",
    width: "20px",
    height: "20px",
  },
}));
export default function GoogleLoginButton(props: any) {
  const {
    clientId,
    onSubmit,
    isShowViewBook,
    contentDetailId,
    searchRequest,
    activeTab,
    isSubscriptionDetail,
  } = props;

  const t = useTranslations("");
  const params = useSearchParams();
  const router = useRouter();
  const mounted = useMounted();
  // const dispatch = useAppDispatch();

  const { classes } = useStyles();
  const servicePath = useAppSelector(getServicePath);
  const viewSettings = useAppSelector(getViewSettings);
  const [OAuth2, setOAuth2] = useState();
  const search = window.location.search;
  const pathname = window.location.pathname;

  const isFullDomain = viewSettings.domainType === DOMAIN_TYPE.FULL_DOMAIN;
  const redirectUrl = isFullDomain
    ? `${window.location.origin}/login`
    : `${window.location.origin}/${servicePath}/login`;

  const handleOAuth2 = () => {
    const data = {
      cacheRoute: window.location.pathname,
      isShowViewBook: isShowViewBook,
      contentId: contentDetailId,
      searchRequest: searchRequest,
      activeTab: activeTab,
    };
    StorageHelper.setSessionObject(STORAGE_KEYS.cacheStorage, data);
    if (isSubscriptionDetail) {
      StorageHelper.setSessionItem(
        STORAGE_KEYS.urlSubscDetail,
        window.location.href
      );
    }
    if (OAuth2) {
      StorageHelper.setSessionItem(
        STORAGE_KEYS.loginType,
        AUTHEN_TYPES.GOOGLE_LOGIN
      );
      OAuth2.requestCode();
    }
  };

  useEffect(() => {
    console.log("window.google", window.google);
  }, []);

  useEffect(() => {
    /* global google */
    if (window.google) {
      const oAuth2 = google.accounts.oauth2.initCodeClient({
        client_id: clientId,
        scope: "profile email",
        ux_mode: "redirect",
        redirect_uri: redirectUrl,
        state: "",
        response_type: "code",
        flow_name: "GeneralOAuthFlow",
        grant_type: "authorization_code",
      });
      setOAuth2(oAuth2);
    }
  }, []);

  // // Handle when success
  useEffect(() => {
    const loginType = StorageHelper.getSessionItem(STORAGE_KEYS.loginType);
    if (
      search &&
      search.includes("?code=") &&
      loginType === AUTHEN_TYPES.GOOGLE_LOGIN
    ) {
      const code = search.split("&")[0].replace("?code=", "");
      
      if (code) {
        // setStopAutoLoad(true);
        const params = {
          authorizeCode: decodeURIComponent(code),
          loginType: AUTHEN_TYPES.GOOGLE_LOGIN,
          redirectUrl: redirectUrl,
        };
        onSubmit(params, AUTHEN_TYPES.GOOGLE_LOGIN);
        StorageHelper.setSessionItem(STORAGE_KEYS.loginType, null);
      } else {
        console.log("code is null");
      }
    }
  }, []);

  // // Handle when Error
  useEffect(() => {
    if (search && search.includes("?error=")) {
      const error = search.split("&")[0].replace("?error=", "");
      if (error) {
        showToast("error", t("toast.error.loginFailed"));
        StorageHelper.setSessionItem(STORAGE_KEYS.loginType, "");
        router.push(`${servicePath ? '/'+servicePath : ''}/login`);
      } else {
        console.log("error is null");
      }
    }
  }, []);

  useEffect(() => {
    if (
      search &&
      (search === "?google=true" || search === "?google=true&fl=true") &&
      pathname &&
      pathname.includes("/login")
    ) {
      if (OAuth2) {
        StorageHelper.setSessionItem(
          STORAGE_KEYS.loginType,
          AUTHEN_TYPES.GOOGLE_LOGIN
        );
        OAuth2.requestCode();
      }
    }
  }, [OAuth2]);

  return (
    <div>
      <AppButton
        type="primary"
        color="danger"
        // htmlType="submit"
        customColor="#fff"
        // loading={isLoading}
        onClick={handleOAuth2}
        style={{ border: "1px solid #6c757d", color: "#000" }}
        className="w-full"
      >
        <img
          src={"/assets/icons/google.svg"}
          style={{ width: "20px", height: "20px" }}
        />
        {t("menu.loginGoogle")}
      </AppButton>
    </div>
  );
}
