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";
import { FirmInitForm } from "../pages/firm";
import { Header } from "../components";

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) {
    throw({statusCode: 400});
  }
  const currentFirm: IFirm = { instance, firm }

  if (isLoading) {
    return <CircularProgress />
  }

  if (isError && error) {
    if (error.statusCode == 405) {
      return <><Header /><FirmInitForm currentFirm={currentFirm} /></>
    }
    if (error.statusCode == 404) {
      throw error;
    }
  }

  currentFirm.entity = data?.data.entity;
  let value: FirmContextType = {
    currentFirm: currentFirm,
    partnerMap: new Map(data?.data.partner_list.map((item: any) => [item.id, item.label])),
  }

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