import { Route, Routes, Link } from "react-router";
import React, { useContext } from "react";
import { useForm, useOne, useTranslation } from "@refinedev/core";
import { FirmContext, FirmContextProvider } from "../../contexts/FirmContext";
import { Header } from "../../components";
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 { translate: t } = useTranslation();
  return (
    <>
      <h1>{t("dashboard.title")}</h1>
      <ul>
        <li><Link to="entities">{t("schemas.entity.resource_plural")}</Link></li>
        <li><Link to="provisions">{t("schemas.provision_template.resource_plural")}</Link></li>
        <li><Link to="templates">{t("schemas.contract_template.resource_plural")}</Link></li>
        <li><Link to="drafts">{t("schemas.contract_draft.resource_plural")}</Link></li>
        <li><Link to="contracts">{t("schemas.contract.resource_plural")}</Link></li>
      </ul>
    </>
  );
}

type FirmInitFormPros = {
  currentFirm: IFirm
}

const FirmInitForm = (props: FirmInitFormPros) => {
  const { currentFirm } = props;
  const { translate: t } = useTranslation();
  const resourceBasePath = `firm`

  const { onFinish } = useForm({
    resource: `${resourceBasePath}/${currentFirm.instance}/${currentFirm.firm}`,
    action: "create",
    redirect: "show",
  });

  return (
    <>
      <h1>Initialization of {`${currentFirm.instance} / ${currentFirm.firm}`}</h1>
      <CrudForm
        schemaName={"CurrentFirmSchema"}
        resourceBasePath={resourceBasePath}
        defaultValue={{corporation: {entity_data: {activity: t("firm.default_activity") }}}}
        uiSchema={{
          corporation: {entity_data: {employees: {"ui:style": {"display": "none"}}}},
        }}
        onSubmit={(data: any) => onFinish(data)}
      />
    </>
  )
}
