import { Route, Routes, Link } from "react-router";
import React, { useContext } from "react";
import { FirmContext, FirmContextProvider } from "../../contexts/FirmContext";
import { Header } from "../../components";
import { useOne } from "@refinedev/core";
import { CrudForm } from "../../lib/crud/components/crud-form";
import { IFirm } from "../../interfaces";
import { EntityRoutes } from "./EntityRoutes";
import { ContractRoutes } from "./ContractRoutes";
import { DraftRoutes } from "./DraftRoutes";
import { TemplateRoutes } from "./TemplateRoutes";
import { ProvisionRoutes } from "./ProvisionRoutes";

export const FirmRoutes = () => {
  return (
    <Routes>
      <Route path="/:instance/:firm/*" element={
        <FirmContextProvider>
          <Header />
          <Routes>
            <Route index element={ <FirmHome /> } />
            <Route path="/entities/*" element={ <EntityRoutes /> } />
            <Route path="/provisions/*" element={ <ProvisionRoutes /> } />
            <Route path="/templates/*" element={ <TemplateRoutes /> } />
            <Route path="/drafts/*" element={ <DraftRoutes /> } />
            <Route path="/contracts/*" element={ <ContractRoutes /> } />
          </Routes>
        </FirmContextProvider>
      } />
    </Routes>
  );
}

const FirmHome = () => {
  const { currentFirm } = useContext(FirmContext);
  const { data: firm, isError, error, isLoading } = useOne({resource: 'firm', id: `${currentFirm.instance}/${currentFirm.firm}/`, errorNotification: false})

  if (isLoading) {
    return <h1>Loading...</h1>
  }

  if (isError && error?.statusCode == 405) {
    return <FirmInitForm currentFirm={currentFirm} />
  }

  return (
    <>
      <h1>This is la firme {currentFirm.instance} / {currentFirm.firm}</h1>
      <ul>
        <li><Link to="entities">Entitées</Link></li>
        <li><Link to="provisions">Templates de Clauses</Link></li>
        <li><Link to="templates">Templates de Contrats</Link></li>
        <li><Link to="drafts">Brouillons</Link></li>
        <li><Link to="contracts">Contrats</Link></li>
      </ul>
    </>

  );
}

type FirmInitFormPros = {
  currentFirm: IFirm
}

const FirmInitForm = (props: FirmInitFormPros) => {
  const { currentFirm } = props;
  return (
    <>
      <h1>Initialization of {`${currentFirm.instance} / ${currentFirm.firm}`}</h1>

      <CrudForm
        schemaName={"CurrentFirmSchemaCreate"}
        resource={`firm/${currentFirm.instance}/${currentFirm.firm}/`}
        uiSchema={{
          corporation: {entity_data: {employees: {"ui:style": {"display": "none"}}}},
        }}
      />
    </>
  )
}
