import React, {
  createContext,
  useContext,
  useState,
} from "react";
import { useAutoComplete } from "@/hooks/useAutoComplete";
import { AutoCompleteItem } from "@/apis/autoCompleteApi";

type DiscoveryContextType = {
  query: string;
  setQuery: (q: string) => void;
  suggestions: AutoCompleteItem[];
  loading: boolean;
  error: string | null;
  clear: () => void;
};

const DiscoveryContext = createContext<DiscoveryContextType | null>(null);

export const DiscoveryProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [query, setQuery] = useState("");
  const { data: suggestions = [], isLoading: loading, error } = useAutoComplete(query);

  const clear = () => {
    setQuery("");
  };

  return (
    <DiscoveryContext.Provider
      value={{ query, setQuery, suggestions, loading, error: error?.message || null, clear }}
    >
      {children}
    </DiscoveryContext.Provider>
  );
};

export const useDiscoveryContext = () => {
  const ctx = useContext(DiscoveryContext);
  if (!ctx)
    throw new Error(
      "useDiscoveryContext must be used within DiscoveryProvider"
    );
  return ctx;
};
