import { useEffect, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
import { useAuthAccess } from "@/contexts/AuthAccessContext";
import { authMeService } from "@/services/fechamento/authMe";
import { NoAccessScreen } from "@/components/auth/NoAccessScreen";

type AuthGateProps = {
  children: ReactNode;
};

const CORE_URL_FALLBACK = "https://core.hgtx.com.br";

export function AuthGate({ children }: AuthGateProps) {
  const {
    loading,
    hasAccess,
    reason,
    errorMessage,
    setAuthState,
  } = useAuthAccess();

  useEffect(() => {
    let mounted = true;

    const bootstrapAccess = async () => {
      const isLogado = GlobalFunctions.isUsuarioLogado();
      if (!isLogado) {
        setAuthState({ loading: false, isAuthenticated: false, hasAccess: false });
        window.location.replace(import.meta.env.VITE_BASE_URL_HGTX_CORE || CORE_URL_FALLBACK);
        return;
      }

      let userEmail = GlobalFunctions.getUsuarioLogado().email;
      if (!userEmail) {
        const transferEmail = GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
        if (typeof transferEmail === "string" && transferEmail.trim()) {
          userEmail = transferEmail.trim();
        }
      }

      if (!userEmail) {
        try {
          await GlobalFunctions.getToken();
          await new Promise((resolve) => setTimeout(resolve, 500));
          userEmail = GlobalFunctions.getUsuarioLogado().email;
        } catch (error) {
          console.error("Erro ao obter token para validação de acesso:", error);
        }
      }

      if (!userEmail) {
        setAuthState({
          loading: false,
          isAuthenticated: false,
          hasAccess: false,
          reason: "erro",
          errorMessage: "Não foi possível identificar o e-mail do usuário logado.",
        });
        return;
      }

      try {
        const me = await authMeService.getMe(userEmail);
        if (!mounted) {
          return;
        }

        if (!me) {
          const estabelecimentoCodigo = String(
            GlobalFunctions.getTransferProperty(TransferAreaProperties.EstabelecimentoCodigo) ?? "",
          ).trim();
          if (estabelecimentoCodigo) {
            try {
              const bootstrap = await authMeService.getBootstrapStatus(estabelecimentoCodigo);
              if (bootstrap.requiresBootstrap) {
                setAuthState({
                  loading: false,
                  isAuthenticated: true,
                  hasAccess: false,
                  reason: "bootstrap",
                  papel: null,
                  me: null,
                  errorMessage: estabelecimentoCodigo,
                });
                return;
              }
            } catch {
              // Mantém fluxo padrão de não cadastrado caso não consiga consultar bootstrap.
            }
          }
          setAuthState({
            loading: false,
            isAuthenticated: true,
            hasAccess: false,
            reason: "nao_cadastrado",
            papel: null,
            me: null,
            errorMessage: null,
          });
          return;
        }

        if (!me.estaAtivo) {
          setAuthState({
            loading: false,
            isAuthenticated: true,
            hasAccess: false,
            reason: "inativo",
            papel: me.papel,
            me,
            errorMessage: null,
          });
          return;
        }

        setAuthState({
          loading: false,
          isAuthenticated: true,
          hasAccess: true,
          papel: me.papel,
          me,
          reason: null,
          errorMessage: null,
        });
      } catch (error) {
        if (!mounted) {
          return;
        }
        setAuthState({
          loading: false,
          isAuthenticated: true,
          hasAccess: false,
          reason: "erro",
          errorMessage: error instanceof Error ? error.message : "Erro ao validar acesso.",
        });
      }
    };

    bootstrapAccess();

    return () => {
      mounted = false;
    };
  }, [setAuthState]);

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-sm text-muted-foreground">Validando acesso...</p>
        </div>
      </div>
    );
  }

  if (!hasAccess) {
    return <NoAccessScreen reason={reason} errorMessage={errorMessage} />;
  }

  return <>{children}</>;
}
