"use client";

import { usePermissions } from "@/hooks/use-permissions";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

interface RequireRoleProps {
  children: React.ReactNode;
  roles?: string[];
  permissions?: string[];
  fallback?: React.ReactNode;
  redirectTo?: string;
}

export function RequireRole({
  children,
  roles,
  permissions,
  fallback,
  redirectTo,
}: RequireRoleProps) {
  const { hasRole, hasPermission, user } = usePermissions();
  const router = useRouter();

  const hasAccess = (() => {
    if (!roles && !permissions) return true;
    // If both specified, either one grants access
    if (roles && hasRole(roles)) return true;
    if (permissions && hasPermission(permissions)) return true;
    return false;
  })();

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

  if (!user) return null;

  if (!hasAccess) {
    if (fallback) return <>{fallback}</>;
    if (redirectTo) return null;
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center text-center">
        <div className="flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
          <svg
            className="h-8 w-8 text-destructive"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
            />
          </svg>
        </div>
        <h2 className="mt-4 text-lg font-semibold">Access Denied</h2>
        <p className="mt-1 text-sm text-muted-foreground">
          You don&apos;t have permission to access this page.
        </p>
      </div>
    );
  }

  return <>{children}</>;
}
