import { salvarConexaoGoogle } from "@/requests/CRM/LogsConexaoGoogle/salvarConexaoGoogle";
import { useAuth } from "@/src/contexts/authContext";
import { useEffect, useState } from "react";

export const BACKEND_URL = "https://api.customax.inf.br";
type GoogleAuthStatus = {
  connected: boolean;
  profile?: {
    name: string;
    email: string;
    picture: string;
    id: string;
  };
};
export const getFrontEnv = () => {
  if (typeof window !== "undefined") {
    if (window.location.href.includes("localhost")) {
      return "local";
    } else if (window.location.href.includes("dev-linksun")) {
      return "dev";
    } else if (window.location.href.includes("homologacao-linksun")) {
      return "hom";
    } else if (window.location.href.includes("sistemalinksun")) {
      return "prod";
    }
  }
  return "";
};
export function useGoogleAuth(lojaId?: string) {
  const { valuesSession } = useAuth();
  const { session } = valuesSession();
  const [status, setStatus] = useState<GoogleAuthStatus>({
    connected: false,
  });
  const sigla = session?.sigla?.toLowerCase();
  const [isStatusVerifyed, setIsStatusVerifyed] = useState(false);
  const { usuario } = useAuth();

  const login = () => {
    if (!lojaId) return;

    // Criamos um objeto com as informações de contexto
    const context = {
      lojaId,
      sigla, // Pegue da sua session/contexto
      // env: getFrontEnv(),
      env: "prod",
      origin: window.location.origin,
    };

    // Convertemos para Base64 para passar pelo parâmetro 'state'
    const state = btoa(JSON.stringify(context));

    window.open(
      `${BACKEND_URL}/auth/google?state=${state}`,
      "googleLogin",
      "width=500,height=600",
    );
  };

  useEffect(() => {
    const handler = (event: MessageEvent) => {
      if (event.data?.type === "google-auth-success") {
        refreshStatus();
        salvarConexaoGoogle({
          cod_usuario_conexao: usuario?.id_usuario,
          cod_loja_conexao: lojaId,
          is_login_conexao: "1",
        });
      } else {
        setIsStatusVerifyed(true);
      }
    };
    window.addEventListener("message", handler);
    return () => window.removeEventListener("message", handler);
  }, []);

  async function uploadImageToS3(file: File, sigla: string) {
    const presigned = await fetch(`${BACKEND_URL}/docs/generate-upload-url`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fileType: file.type, sigla }),
    }).then(r => r.json());

    const formData = new FormData();

    Object.entries(presigned.fields).forEach(([k, v]) => {
      formData.append(k, v as string);
    });

    formData.append("file", file);

    const uploadRes = await fetch(presigned.uploadUrl, {
      method: "POST",
      body: formData,
    });

    if (!uploadRes.ok) {
      throw new Error("Erro upload S3");
    }

    // 🔥 RETORNAR A KEY
    return presigned.getUrl;
  }

  const refreshStatus = async () => {
    setIsStatusVerifyed(false);
    if (!lojaId) {
      setIsStatusVerifyed(true);
      return;
    }
    const res = await fetch(
      // `${BACKEND_URL}/auth/status?lojaId=${lojaId}&sigla=${sigla}&env=${getFrontEnv()}`,
      `${BACKEND_URL}/auth/status?lojaId=${lojaId}&sigla=${sigla}&env=${"prod"}`,
      { credentials: "include" },
    );
    setStatus(await res.json());

    setIsStatusVerifyed(true);
  };

  const logout = async () => {
    await fetch(`${BACKEND_URL}/auth/logout`, {
      method: "POST", // Mude para POST
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        lojaId,
        sigla,
        // env: getFrontEnv(),
        env: "prod",
      }),
      credentials: "include",
    });
    salvarConexaoGoogle({
      cod_usuario_conexao: usuario?.id_usuario,
      cod_loja_conexao: lojaId,
      is_login_conexao: "0",
    });
    setStatus({ connected: false });
  };

  useEffect(() => {
    refreshStatus();
  }, [lojaId]);

  return {
    ...status,
    login,
    logout,
    uploadImageToS3,
    refreshStatus,
    isStatusVerifyed,
  };
}
