import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';

interface RouteGuardProps {
  children: React.ReactNode;
  requiredRole?: 'user' | 'provider' | 'admin';
}

// Please add the pages that can be accessed without logging in to PUBLIC_ROUTES.
const PUBLIC_ROUTES = [
  '/',
  '/sign-in*',
  '/sign-up*',
  '/login',
  '/403',
  '/404',
  '/about',
  '/contact',
  '/explore',
  '/create-trip',
  '/provider/info',
  '/trips',
  '/trips/*',
  '/trip/*',
  '/journal',
  '/journal/*',
  '/privacy',
  '/terms'
];

function matchPublicRoute(path: string, patterns: string[]) {
  return patterns.some(pattern => {
    if (pattern.includes('*')) {
      const regex = new RegExp('^' + pattern.replace('*', '.*') + '$');
      return regex.test(path);
    }
    return path === pattern;
  });
}

export function RouteGuard({ children, requiredRole }: RouteGuardProps) {
  const { user, profile, loading } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    if (loading) return;

    const isPublic = matchPublicRoute(location.pathname, PUBLIC_ROUTES);

    if (!user && !isPublic) {
      navigate('/sign-in', { state: { from: location.pathname }, replace: true });
    } else if (user && requiredRole && profile?.role !== requiredRole && profile?.role !== 'admin') {
      // Admin can access everything, others restricted by role
      navigate('/403', { replace: true });
    }
  }, [user, profile, loading, location.pathname, navigate, requiredRole]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  return <>{children}</>;
}
