import PropTypes from "prop-types";
import { createContext, useContext, useState, useEffect } from "react";

// Create context
const CompaniesContext = createContext({
  companies: [],
  setCompanies: () => {},
});

// Provider
export const CompaniesProvider = ({ children, initialCompanies = [] }) => {
  const [companies, setCompanies] = useState(initialCompanies);

  // Update companies whenever initialCompanies changes
  useEffect(() => {
    if (initialCompanies && initialCompanies.length > 0) {
      setCompanies(initialCompanies);
    }
  }, [initialCompanies]);

  return (
    <CompaniesContext.Provider value={{ companies, setCompanies }}>
      {children}
    </CompaniesContext.Provider>
  );
};

CompaniesProvider.propTypes = {
  children: PropTypes.any,
  initialCompanies: PropTypes.array,
};

// Hook for consuming
export const useCompanies = () => useContext(CompaniesContext);
