import { createContext, useContext, type ReactNode } from "react";
import type { SightingWidgetType } from "../types/types";
import { useSightingFeed } from "../hooks/useSightingFeed";

type SightingFeedContextType = {
  sightings: (SightingWidgetType | null | undefined)[];
  selectedRef: number | null;
  setSelectedRef: (ref: number | null) => void;
  effectiveSelected: SightingWidgetType | null;
  mostRecent: SightingWidgetType | null;
  side: string;
  isPending: boolean;
  noSighting: boolean;
};

type SightingFeedProviderProps = {
  url: string;
  children: ReactNode;
  side: string;
};

const SightingFeedContext = createContext<SightingFeedContextType | undefined>(
  undefined
);

export const SightingFeedProvider = ({
  children,
  url,
  side,
}: SightingFeedProviderProps) => {
  const {
    sightings,
    selectedRef,
    setSelectedRef,
    effectiveSelected,
    mostRecent,
    isPending,
    noSighting,
  } = useSightingFeed(url);

  return (
    <SightingFeedContext.Provider
      value={{
        sightings,
        selectedRef,
        setSelectedRef,
        effectiveSelected,
        mostRecent,
        side,
        isPending,
        noSighting,
      }}
    >
      {children}
    </SightingFeedContext.Provider>
  );
};

// eslint-disable-next-line react-refresh/only-export-components
export const useSightingFeedContext = () => {
  const ctx = useContext(SightingFeedContext);
  if (!ctx)
    throw new Error(
      "useSightingFeedContext must be used within SightingFeedProvider"
    );
  return ctx;
};
