"use client";

import * as React from "react";

import { fetchDashboardWidgetsBatch } from "@/app/customer/[tenant]/dashboard/_lib/dashboard-widgets-api";
import type { DashboardWidgetPayload } from "@/app/customer/[tenant]/dashboard/_lib/dashboard-widgets-server-api";
import { useImpersonationScopeRefresh } from "@/app/customer/_lib/admin/use-impersonation-scope-refresh";

export type DashboardWidgetBatchEntry = DashboardWidgetPayload;

type DashboardWidgetsContextValue = {
  widgets: Record<string, DashboardWidgetBatchEntry>;
  loading: boolean;
  refresh: () => Promise<void>;
  getEntry: (layoutId: string) => DashboardWidgetBatchEntry | undefined;
};

const DashboardWidgetsContext = React.createContext<DashboardWidgetsContextValue | null>(null);

export function DashboardWidgetsProvider({
  tenant,
  widgetIds,
  children,
}: {
  tenant: string;
  widgetIds: string[];
  children: React.ReactNode;
}) {
  const [widgets, setWidgets] = React.useState<Record<string, DashboardWidgetBatchEntry>>({});
  const [loading, setLoading] = React.useState(widgetIds.length > 0);
  const widgetIdsKey = widgetIds.join("|");

  const load = React.useCallback(async () => {
    if (!tenant || widgetIds.length === 0) {
      setWidgets({});
      setLoading(false);
      return;
    }

    setLoading(true);
    const result = await fetchDashboardWidgetsBatch(tenant, widgetIds);
    setWidgets(result.widgets);
    setLoading(false);
  }, [tenant, widgetIdsKey]); // eslint-disable-line react-hooks/exhaustive-deps -- keyed by join

  useImpersonationScopeRefresh(() => {
    void load();
  });

  React.useEffect(() => {
    void load();
  }, [load]);

  const value = React.useMemo(
    (): DashboardWidgetsContextValue => ({
      widgets,
      loading,
      refresh: load,
      getEntry: (layoutId: string) => widgets[layoutId],
    }),
    [widgets, loading, load],
  );

  return <DashboardWidgetsContext.Provider value={value}>{children}</DashboardWidgetsContext.Provider>;
}

export function useDashboardWidgetsBatch() {
  return React.useContext(DashboardWidgetsContext);
}
