import { Navigate, useLocation } from "react-router-dom";
import { useEffect, useState } from "react";
import LoadingSpinner from "../components/partials/LoadingSpinner";

interface IsMemberProps {
  children: React.ReactNode;
}

const IsCompleted: React.FC<IsMemberProps> = ({ children }) => {
  const location = useLocation();
  const [redirectTo, setRedirectTo] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    try {
      const userData = JSON.parse(localStorage.getItem('user') || '{}');
      const stepCount = userData.registration_step || 0;
      
      // Check if registration is incomplete
      const incomplete = stepCount < 16;
      
      // Determine which step to redirect to if incomplete
      if (incomplete) {
        if (stepCount < 4) {
          setRedirectTo('/registration/step-1');
        } else if (stepCount < 8) {
          setRedirectTo('/registration/step-2');
        } else if (stepCount < 12) {
          setRedirectTo('/registration/step-3');
        } else if (stepCount < 16) {
          setRedirectTo('/registration/step-4');
        }
      }
    } catch (error) {
      console.error("Error parsing user data:", error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  if (isLoading) {
    return <LoadingSpinner text="Checking registration status" />;
  }

  if (redirectTo) {
    return <Navigate to={redirectTo} state={{ from: location }} replace />;
  }

  return <>{children}</>;
};

export default IsCompleted;
