import { getShows, Show } from "@/apis/showApi";
import { createContext, useContext, useEffect, useState } from "react";

type ShowContextType = {
  shows: Show[];
  loading: boolean;
  error: string | null;
};

const ShowContext = createContext<ShowContextType | null>(null);

export const ShowProvider = ({ children }: { children: React.ReactNode }) => {
  const [shows, setShows] = useState<Show[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const data = await getShows();
        setShows(data);
      } catch {
        setError("Failed to fetch shows");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

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

export const useShowContext = () => {
  const ctx = useContext(ShowContext);
  if (!ctx)
    throw new Error("useShowContext must be used within a ShowProvider");
  return ctx;
};
