import React from "react";
import { useParams } from "react-router-dom";

import ComponentLoader from "../containers/ComponentLoader";
import { useUser } from "../contexts/UserContext";
import { hasAccess } from "../util/has_access";

import { usePage } from "./Page";

export interface ContribInlinesProps {
  contribParams?: Record<string | number | symbol, unknown>;
  data?: unknown;
  variant?: string;
}

export const ContribInlines: React.FC<ContribInlinesProps> = ({ contribParams, data, variant }) => {
  const params = useParams();
  const page = usePage();
  const { user } = useUser();
  const componentVariant = variant ?? "inline";

  contribParams = { ...params, ...contribParams };

  return (
    <>
      {page.contrib
        .filter(
          (operation) =>
            operation.method === "GET" && operation.component?.variant === componentVariant,
        )
        .map((operation) => {
          if (operation.component?.predicate && data && !operation.component?.predicate(data))
            return null;

          if (!hasAccess(user, operation.component?.permission, operation.component?.group))
            return null;

          const mapContribParams = operation.paramsMap
            ? operation.paramsMap[page.routeId]
            : undefined;
          const operationParams = mapContribParams
            ? mapContribParams(contribParams)
            : contribParams;
          return (
            <ComponentLoader key={operation.id} operation={operation} params={operationParams} />
          );
        })}
    </>
  );
};
