/* eslint-disable @typescript-eslint/no-unused-vars */
import React from "react";
import { Company } from "../types";

export interface ICompanyContextType {
  companies: Company[];
  addCompanies: (c: Company[]) => void;
  addCompany: (c: Company) => void;
  updateCompany: (c: Company) => void;
  getCompany: (id: string) => Company | undefined;
  getCompanies: () => Company[];
}

const defaultValue: ICompanyContextType = {
  companies: [],
  addCompanies: (c: Company[]) => undefined,
  addCompany: (c: Company) => undefined,
  updateCompany: (c: Company) => undefined,
  getCompany: (id: string) => ({}) as Company,
  getCompanies: () => [],
};

export const CompanyContext = React.createContext<ICompanyContextType>(
  defaultValue as ICompanyContextType,
);

const CompanyProvider: React.FC<React.ReactNode> = ({ children }) => {
  const [companies, setCompanies] = React.useState<Company[]>([] as Company[]);

  const addCompanies = (c: Company[]) => {
    console.log(c);
    setCompanies([...c]);
  };

  const addCompany = (c: Company) => {
    setCompanies([...companies, c]);
  };

  const updateCompany = (c: Company) => {
    companies.filter((comp: Company) => {
      if (c.id == comp.id) {
        comp = {
          ...comp,
          ...c,
        };
        setCompanies([...companies]);
      }
    });
  };

  const getCompany = (s: string) => {
    return companies.find((comp: Company) => comp.id == s);
  };

  const getCompanies = () => {
    return companies;
  };

  return (
    <CompanyContext.Provider
      value={{
        companies,
        addCompany,
        addCompanies,
        updateCompany,
        getCompany,
        getCompanies,
      }}
    >
      {children}
    </CompanyContext.Provider>
  );
};

export default CompanyProvider;
