import { createContext, ReactNode, useContext, useState } from "react";

// Define the shape of the context state and actions
type MessageContextType = {
  isVisible: boolean; // Indicates if the message is visible
  message: string; // The message to be displayed
  showMessage: (message: string) => void; // Function to show the message
  hideMessage: () => void; // Function to hide the message
}

// Create the context with default values
const MessageContext = createContext<MessageContextType>({
  isVisible: false,
  message: "",
  showMessage: () => {},
  hideMessage: () => {}
});

// Define the props for the MessageContextProvider component
type MessageContextProviderProps = {
  children: ReactNode; // The child components that will have access to the context
}

// Create the provider component
export const MessageContextProvider = ({children}: MessageContextProviderProps) => {
  const [isVisible, setIsVisible] = useState<boolean>(false); // State to track visibility of the message
  const [message, setMessage] = useState<string>(""); // State to track the message content

  // Function to show the message and hide it after 3 seconds
  const showMessage = (message: string) => {
    setIsVisible(true);
    setMessage(message);
    setTimeout(() => {
      setIsVisible(false);
      setMessage("");
    }, 3000);
  };

  // Function to hide the message immediately
  const hideMessage = () => {
    setIsVisible(false);
    setMessage("");
  };

  // Provide the context value to child components
  const value = {isVisible, message, showMessage, hideMessage};
  return <MessageContext.Provider value={value}>{children}</MessageContext.Provider>
}

// Custom hook to use the MessageContext
export const useMessage = () => {
  if(MessageContext === undefined){
    throw new Error("useMessage debe se usado dentro de un MessageContextProvider");
  }
  return useContext(MessageContext);
};