import { useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";

/**
 * Componente que detecta tokens de recuperação na URL e redireciona para /reset-password
 * Funciona tanto com query string (?token=xxx) quanto com hash (#access_token=xxx)
 */
const RecoveryRedirect: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    console.log("[RecoveryRedirect] Verificando URL...");
    console.log("[RecoveryRedirect] Pathname:", location.pathname);
    console.log("[RecoveryRedirect] Search:", location.search);
    console.log("[RecoveryRedirect] Hash:", location.hash);

    let shouldRedirect = false;

    // Verificar query string: ?token=xxx&type=recovery
    const searchParams = new URLSearchParams(location.search);
    const queryToken = searchParams.get("token");
    const queryType = searchParams.get("type");

    if (queryToken && queryType === "recovery") {
      console.log(
        "[RecoveryRedirect] ✅ Token de recovery no query string detectado"
      );
      shouldRedirect = true;
    }

    // Verificar hash: #access_token=xxx&type=recovery
    if (location.hash) {
      const hashParams = new URLSearchParams(location.hash.substring(1));
      const hashToken = hashParams.get("access_token");
      const hashType = hashParams.get("type");

      if (hashToken && hashType === "recovery") {
        console.log(
          "[RecoveryRedirect] ✅ Token de recovery no hash detectado"
        );
        shouldRedirect = true;
      }
    }

    if (shouldRedirect) {
      console.log("[RecoveryRedirect] 🔄 Redirecionando para /reset-password");
      // Preservar os parâmetros e redirecionar
      navigate(`/reset-password${location.search}${location.hash}`, {
        replace: true,
      });
    } else {
      console.log("[RecoveryRedirect] ℹ️ Nenhum token de recovery detectado");
    }
  }, [location, navigate]);

  return null; // Componente invisível
};

export default RecoveryRedirect;
