import React, {
  createContext,
  useContext,
  PropsWithChildren,
  useRef,
} from 'react';
import {createStore, StoreApi, useStore} from 'zustand';

export interface TabStore {
  tabIndex: number;
  setTabIndex: (index: number) => void;
}

type TabStoreApi = StoreApi<TabStore>;

const TabStoreContext = createContext<TabStoreApi | null>(null);

export const TabStoreProvider = ({
  tabIndex = 0,
  children,
}: PropsWithChildren & {tabIndex?: number}) => {
  const storeRef = useRef(
    createStore<TabStore>(set => ({
      tabIndex,
      setTabIndex: index => set({tabIndex: index}),
    })),
  );

  return (
    <TabStoreContext.Provider value={storeRef.current!}>
      {children}
    </TabStoreContext.Provider>
  );
};

export const useTabStore = <T,>(selector: (state: TabStore) => T): T => {
  const store = useContext(TabStoreContext);
  if (!store) {
    throw new Error('Missing <TabStoreProvider>');
  }
  return useStore(store, selector);
};
