import React, { useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { toast } from 'sonner';

const MemberRoute = ({ children }) => {
  const { user, loading } = useAuth();
  const [hasShownToast, setHasShownToast] = React.useState(false);

  useEffect(() => {
    // Show toast only once when user is not active
    if (!loading && user && user.status !== 'active' && !hasShownToast) {
      toast.error('Active membership required. Please complete your payment to access this feature.', {
        duration: 5000
      });
      setHasShownToast(true);
    }
  }, [user, loading, hasShownToast]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#FDFCF8]">
        <p className="text-[#6B708D]">Loading...</p>
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" />;
  }

  // Allow admins to bypass payment requirement
  if (user.role === 'admin') {
    return children;
  }

  // Check if user is an active member
  if (user.status !== 'active') {
    return <Navigate to="/plans" />;
  }

  return children;
};

export default MemberRoute;
