import { createContext, useContext } from 'react';
import type { SearchKeywordOption } from '../../../components/search';
import type { MarkdownDocument } from '../../../components/markdownPreview';
import type { LoadedSampleEntry, SampleEntry } from '../../../samples/registry';
import type { SavedLayoutRecord } from '../../../views/play/layoutStorage';
import type {
  ApiSectionKey,
  ChatSectionKey,
  PlanSectionKey,
  PlaySidebarKey,
  TopMenuKey,
} from '../routes';

export type MainLayoutContextValue = {
  topMenu: TopMenuKey;
  selectedDocsMenu: string;
  selectedApiMenu: ApiSectionKey;
  selectedPlanMenu: PlanSectionKey;
  selectedChatMenu: ChatSectionKey;
  selectedPlayMenu: PlaySidebarKey;
  activePlanQuickFilter: 'working' | 'release-pending-main' | 'automation-failed' | null;
  planQuickFilterRequestKey: number;
  initialSelectedPlanId: number | null;
  initialSelectedWorkId: string | null;
  selectedDocs: MarkdownDocument[];
  docsDocuments: MarkdownDocument[];
  componentSampleEntries: SampleEntry[];
  widgetSampleEntries: SampleEntry[];
  componentSamples: LoadedSampleEntry[];
  widgetSamples: LoadedSampleEntry[];
  savedLayouts: SavedLayoutRecord[];
  savedLayoutsReady: boolean;
  setSavedLayouts: (layouts: SavedLayoutRecord[]) => void;
  searchOptions: SearchKeywordOption[];
};

const MainLayoutContext = createContext<MainLayoutContextValue | null>(null);

export const MainLayoutContextProvider = MainLayoutContext.Provider;

export function useMainLayoutContext() {
  const context = useContext(MainLayoutContext);

  if (!context) {
    throw new Error('useMainLayoutContext must be used within MainLayoutContextProvider.');
  }

  return context;
}
