import {
  createContext,
  useContext,
  useMemo,
  type ReactNode,
} from "react";

import { useSettingsGroups, type GroupRow } from "@/hooks/useSettingsGroups";

export type { GroupRow };

type GroupsContextValue = {
  groups: GroupRow[];
  status: "idle" | "loading" | "error";
  error: string;
  refresh: () => Promise<void>;
};

const GroupsContext = createContext<GroupsContextValue | null>(null);

export function GroupsProvider({ children }: { children: ReactNode }) {
  const { groups, status, error, refresh } = useSettingsGroups(true);

  const value = useMemo(
    () => ({
      groups,
      status,
      error,
      refresh,
    }),
    [error, groups, refresh, status],
  );

  return (
    <GroupsContext.Provider value={value}>{children}</GroupsContext.Provider>
  );
}

export function useGroups() {
  const ctx = useContext(GroupsContext);
  if (!ctx) {
    throw new Error("useGroups must be used within a GroupsProvider");
  }
  return ctx;
}
