import {
  getStreamingImages,
  StreamingServiceRaw,
} from "@/apis/streamingServiceApi";
import { createContext, useContext } from "react";
import React from "react";

type StreamingServiceContextType = {
  streamingServices: Record<string, string>;
  loading: boolean;
  error: string | null;
};

const StreamingServiceContext =
  createContext<StreamingServiceContextType | null>(null);

export const StreamingServiceProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [streamingServices, setStreamingServices] = React.useState<
    Record<string, string>
  >({});
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    (async () => {
      try {
        const data: StreamingServiceRaw[] = await getStreamingImages();

        const mapped = Object.fromEntries(data.map((s) => [s.key, s.value]));
        setStreamingServices(mapped);
      } catch {
        setError("Failed to fetch streaming services");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  return (
    <StreamingServiceContext.Provider
      value={{ streamingServices, loading, error }}
    >
      {children}
    </StreamingServiceContext.Provider>
  );
};

export const useStreamingServiceContext = () => {
  const ctx = useContext(StreamingServiceContext);
  if (!ctx)
    throw new Error(
      "useStreamingServiceContext must be used within a StreamingServiceProvider"
    );
  return ctx;
};
