'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { Permission, hasPermission, hasAnyPermission, isAdmin, isSuperAdmin } from '@/lib/auth/roles';
import { Role } from '@/types/auth';

interface ProtectedRouteProps {
  children: React.ReactNode;
  requiredPermissions?: Permission[];
  anyPermission?: Permission[];
  requireAdmin?: boolean;
  requireSuperAdmin?: boolean;
  fallback?: React.ReactNode;
  redirectTo?: string;
}

export function ProtectedRoute({
  children,
  requiredPermissions,
  anyPermission,
  requireAdmin,
  requireSuperAdmin,
  fallback,
  redirectTo = '/dashboard',
}: ProtectedRouteProps) {
  const { user, loading } = useAuth();
  const router = useRouter();

  const hasAccess = (): boolean => {
    if (!user) return false;

    const userRole = user.role as Role;

    if (requireSuperAdmin && !isSuperAdmin(userRole)) return false;
    if (requireAdmin && !isAdmin(userRole)) return false;

    if (requiredPermissions?.length) {
      const hasAll = requiredPermissions.every(p => hasPermission(userRole, p));
      if (!hasAll) return false;
    }

    if (anyPermission?.length) {
      if (!hasAnyPermission(userRole, anyPermission)) return false;
    }

    return true;
  };

  useEffect(() => {
    if (!loading && !hasAccess()) {
      router.push(redirectTo);
    }
  }, [user, loading, redirectTo, router]);

  if (loading) {
    return fallback || <LoadingSpinner />;
  }

  if (!hasAccess()) {
    return fallback || null;
  }

  return <>{children}</>;
}

function LoadingSpinner() {
  return (
    <div className="flex items-center justify-center min-h-[200px]">
      <div className="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin" />
    </div>
  );
}
