import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { HqListColumnKey, HqListColumnPref, HqListColumnPrefsMap } from '@dukang/shared-types';
import { request } from './api';

type Ctx = {
  prefs: HqListColumnPrefsMap;
  ready: boolean;
  setPrefs: (next: HqListColumnPrefsMap) => void;
  save: (listKey: HqListColumnKey, next: HqListColumnPref | null) => Promise<void>;
};

const ListColumnPrefsContext = createContext<Ctx>({
  prefs: {},
  ready: false,
  setPrefs: () => {},
  save: async () => {},
});

export function ListColumnPrefsProvider({
  initial,
  children,
}: {
  initial?: HqListColumnPrefsMap;
  children: ReactNode;
}) {
  const [prefs, setPrefs] = useState<HqListColumnPrefsMap>(initial ?? {});
  const [ready] = useState(true);

  useEffect(() => {
    if (initial) setPrefs(initial);
  }, [initial]);

  const save = useCallback(async (listKey: HqListColumnKey, next: HqListColumnPref | null) => {
    const res = await request<{ listColumnPrefs: HqListColumnPrefsMap }>(
      `/admin/me/list-columns/${listKey}`,
      {
        method: 'PUT',
        body: JSON.stringify(
          next
            ? { order: next.order, hidden: next.hidden, widths: next.widths }
            : { reset: true },
        ),
      },
    );
    setPrefs(res.listColumnPrefs ?? {});
  }, []);

  const value = useMemo(() => ({ prefs, ready, setPrefs, save }), [prefs, ready, save]);
  return <ListColumnPrefsContext.Provider value={value}>{children}</ListColumnPrefsContext.Provider>;
}

export function useListColumnPrefs() {
  return useContext(ListColumnPrefsContext);
}
