import {
  createContext,
  PropsWithChildren,
  useCallback,
  useContext,
  useMemo,
  useState,
} from 'react';

type MasterSelectionContextValue = {
  constructionId: string;
  assigneeId: string;
  setConstructionId: (value: string) => void;
  setAssigneeId: (value: string) => void;
};

const MasterSelectionContext = createContext<MasterSelectionContextValue | null>(null);

export function MasterSelectionProvider({ children }: PropsWithChildren) {
  const [constructionId, setConstructionId] = useState('');
  const [assigneeId, setAssigneeId] = useState('');

  const setConstructionIdCb = useCallback((value: string) => {
    setConstructionId(value);
  }, []);

  const setAssigneeIdCb = useCallback((value: string) => {
    setAssigneeId(value);
  }, []);

  const value = useMemo<MasterSelectionContextValue>(
    () => ({
      constructionId,
      assigneeId,
      setConstructionId: setConstructionIdCb,
      setAssigneeId: setAssigneeIdCb,
    }),
    [constructionId, assigneeId, setConstructionIdCb, setAssigneeIdCb]
  );

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

export function useMasterSelection(): MasterSelectionContextValue {
  const ctx = useContext(MasterSelectionContext);
  if (!ctx) {
    throw new Error('useMasterSelection は MasterSelectionProvider 内で使用してください。');
  }
  return ctx;
}
