"use client";

import { createContext, useContext, useMemo, useReducer } from "react";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { BuilderState, BuilderAction, BuilderProviderProps } from "./types";
import { INITIAL_STATE } from "./constants";
import { builderReducer } from "./reducer";

const BuilderStateContext = createContext<BuilderState | undefined>(undefined);
const BuilderDispatchContext = createContext<((action: BuilderAction) => void) | undefined>(undefined);

export function BuilderProvider({ children, initialState }: BuilderProviderProps) {
  const [state, dispatch] = useReducer(builderReducer, initialState ?? INITIAL_STATE);

  const memoizedState = useMemo(() => state, [state]);
  const memoizedDispatch = useMemo(() => dispatch, []);

  return (
    <BuilderStateContext.Provider value={memoizedState}>
      <BuilderDispatchContext.Provider value={memoizedDispatch}>{children}</BuilderDispatchContext.Provider>
    </BuilderStateContext.Provider>
  );
}

export function useBuilderState(): BuilderState {
  const ctx = useContext(BuilderStateContext);
  if (!ctx) {
    throw new Error("useBuilderState must be used within BuilderProvider");
  }
  return ctx;
}

export function useBuilderDispatch(): (action: BuilderAction) => void {
  const ctx = useContext(BuilderDispatchContext);
  if (!ctx) {
    throw new Error("useBuilderDispatch must be used within BuilderProvider");
  }
  return ctx;
}

export function useBuilderSelectedScreen(): BuilderScreen | undefined {
  const state = useBuilderState();
  return state.screens.find((screen) => screen.id === state.selectedScreenId);
}
