import {
  createContext,
  useContext,
  useMemo,
  useSyncExternalStore,
  type ReactNode,
} from "react";
import {
  dictionarySessionStore,
  type DictionarySessionStore,
  type DictionaryState,
} from "./dictionaryState";
import {
  dictionaryLabel,
  dictionaryOptions,
} from "./dictionaryLabels";
import type { DictionaryName } from "./dictionaryTypes";

interface DictionaryContextValue extends DictionaryState {
  load: (sessionKey: string) => Promise<unknown>;
  retry: (sessionKey: string) => Promise<unknown>;
  clear: () => void;
  label: (
    name: DictionaryName,
    code: string | null | undefined,
  ) => string;
  options: (name: DictionaryName) => readonly {
    code: string;
    label: string;
    sortNo: number;
  }[];
}

const DictionaryContext = createContext<DictionaryContextValue | null>(null);

export function DictionaryProvider({
  children,
  store = dictionarySessionStore,
}: {
  children: ReactNode;
  store?: DictionarySessionStore;
}) {
  const state = useSyncExternalStore(
    store.subscribe,
    store.getSnapshot,
    store.getSnapshot,
  );
  const value = useMemo<DictionaryContextValue>(
    () => ({
      ...state,
      load: (sessionKey) => store.load(sessionKey),
      retry: (sessionKey) => store.retry(sessionKey),
      clear: () => store.clear(),
      label: (name, code) =>
        state.data
          ? dictionaryLabel(state.data, name, code)
          : "字典加载中",
      options: (name) =>
        state.data ? dictionaryOptions(state.data, name) : [],
    }),
    [state, store],
  );
  return (
    <DictionaryContext.Provider value={value}>
      {children}
    </DictionaryContext.Provider>
  );
}

export function useDictionaries(): DictionaryContextValue {
  const value = useContext(DictionaryContext);
  if (!value) {
    throw new Error("useDictionaries必须在DictionaryProvider内使用");
  }
  return value;
}
