'use client';

import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useReducer,
} from 'react';

import { HooksFeedType } from '@/components/hooksPlayer/constants';

type HooksFeedState = {
  /**
   * The current feed context ID
   */
  feedId?: HooksFeedType;
  /**
   * The ID of the hook setting the context of the current feed
   */
  hookId?: string;
  /**
   * The user handle setting the context of the current feed
   */
  userHandle?: string;
  /**
   * The ID of the current hook to display
   */
  feedCurrentHookId?: string;
  /**
   * The index of the current hook in the feed
   */
  feedCurrentIndex?: number;
};

type HooksFeedContextType = HooksFeedState & {
  updateState: (updates: Partial<HooksFeedState>) => void;
};

const HooksFeedContext = createContext<HooksFeedContextType>({
  feedId: undefined,
  hookId: undefined,
  userHandle: undefined,
  feedCurrentHookId: undefined,
  feedCurrentIndex: undefined,
  updateState: () => ({}),
});

export const HooksFeedProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [state, updateState] = useReducer(
    (prevState: HooksFeedState, stateUpdates: Partial<HooksFeedState>) => ({
      ...prevState,
      ...stateUpdates,
    }),
    {}
  );

  const value = useMemo(
    () => ({ ...state, updateState }),
    [state, updateState]
  );

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

export function useHooksFeedContext(
  context?: Pick<HooksFeedState, 'hookId' | 'userHandle' | 'feedId'>
) {
  const hooksFeedContext = useContext(HooksFeedContext);

  const hasContext = context != null;
  const { feedId, hookId, userHandle } = context || {};
  const { updateState } = hooksFeedContext;

  useEffect(() => {
    if (hasContext) {
      updateState({ feedId, hookId, userHandle });
    }
  }, [hasContext, feedId, hookId, userHandle, updateState]);

  return useMemo(
    () =>
      hasContext
        ? { ...hooksFeedContext, feedId, hookId, userHandle }
        : hooksFeedContext,
    [hooksFeedContext, hasContext, feedId, hookId, userHandle]
  );
}
