import React, { createContext, PropsWithChildren } from 'react';
import { IFirm } from "../interfaces";
import { useParams } from "react-router";
import { useOne } from "@refinedev/core";
import { CircularProgress } from "@mui/material";

type FirmContextType = {
  currentFirm: IFirm,
  partnerMap?: Map<string, string>
}

export const FirmContext = createContext<FirmContextType>(
  {} as FirmContextType
);


export const FirmContextProvider: React.FC<PropsWithChildren> = ({ children }: PropsWithChildren) => {
  const { instance, firm } = useParams<IFirm>();
  const { data, isError, error, isLoading } = useOne({resource: 'firm', id: `${instance}/${firm}/`, errorNotification: false});

  if (instance === undefined || firm === undefined) {
    return "Error"
  }

  if (isLoading) {
    return <CircularProgress />
  }

  let value: FirmContextType = {
    currentFirm: {instance, firm}
  }
  if (!isError || error?.statusCode != 405) {
    value.currentFirm.entity = data?.data.entity;
    value.partnerMap = new Map(data?.data.partner_list.map((item: any) => [item.id, item.label]));
  }

  return (
    <FirmContext.Provider value={value} >
      { children }
    </FirmContext.Provider>
  );
}
