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

export type CycleContextType = {
  selectedCycleId: number | null;
  setSelectedCycleId: (cycleId: number | null) => void;
};

const CycleContext = createContext<CycleContextType | null>(null);

export const CycleProvider = ({ children }: { children: ReactNode }) => {
  const [selectedCycleId, setSelectedCycleId] = useState<number | null>(null);

  const value = useMemo(
    () => ({ selectedCycleId, setSelectedCycleId }),
    [selectedCycleId],
  );

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

export const useCycleContext = () => {
  const context = useContext(CycleContext);
  if (!context)
    throw new Error('useCycleContext must be used within a CycleProvider');
  return context;
};
