import { useEffect, useRef } from "react";
import { PublishedStakeholdersManagePanel } from "../../app/(app)/create/screens/select/PublishedStakeholdersManagePanel";

function StakeholdersFetchMock({ children }) {
  const origRef = useRef(undefined);
  if (origRef.current === undefined) {
    origRef.current = globalThis.fetch;
    globalThis.fetch = async (input, init) => {
      const url =
        typeof input === "string"
          ? input
          : input instanceof URL
            ? input.href
            : input.url;
      if (url.includes("/stakeholders")) {
        if (init?.method && init.method !== "GET") {
          return new Response(JSON.stringify({ ok: true }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        }
        return new Response(JSON.stringify({ stakeholders: [] }), {
          status: 200,
          headers: { "Content-Type": "application/json" },
        });
      }
      return origRef.current(input, init);
    };
  }
  useEffect(() => {
    return () => {
      if (origRef.current) {
        globalThis.fetch = origRef.current;
      }
    };
  }, []);
  return children;
}

export default {
  title: "Pages/Create Flow/Published stakeholders",
  component: PublishedStakeholdersManagePanel,
  parameters: {
    layout: "fullscreen",
    docs: {
      description: {
        component:
          "Manage invites on a published rule. Fetch is stubbed empty in this story.",
      },
    },
  },
  decorators: [
    (Story) => (
      <StakeholdersFetchMock>
        <div className="min-h-screen bg-[var(--color-surface-default-primary)] p-8">
          <Story />
        </div>
      </StakeholdersFetchMock>
    ),
  ],
};

export const Default = {
  args: {
    ruleId: "storybook-rule",
  },
};
