import { Route, Routes } from "react-router";
import { CircularProgress } from "@mui/material";
import React, { useContext, useState } from "react";
import { useOne } from "@refinedev/core";
import { BaseForm } from "../../lib/crud/components/base-form";
import { ForeignKeyReference, ForeignKeySchema } from "../../lib/crud/components/widgets/foreign-key";

import { FirmContext } from "../../contexts/FirmContext";
import List from "./base-page/List";
import Edit from "./base-page/Edit";
import New from "./base-page/New";

type Draft = {
  id: string,
  label: string
}

export const DraftRoutes = () => {
  return (
    <Routes>
      <Route index element={ <ListDraft /> } />
      <Route path="/edit/:record_id" element={ <EditDraft /> } />
      <Route path="/create" element={ <CreateDraft /> } />
    </Routes>
  );
}

const ListDraft = () => {
  const columns = [
    { field: "label", headerName: "Label", flex: 1 },
  ];
  return <List<Draft> resource={`contracts/drafts`} columns={columns} />
}

const EditDraft = () => {
  return <Edit<Draft> resource={`contracts/drafts`} schemaName={"ContractDraft"} />
}

type ForeignKeySubSchema = ForeignKeySchema & {
  properties: { [key: string]: { foreignKey: { reference: ForeignKeyReference } } }
}

const CreateDraft = () => {
  const [chosenDraft, setChosenDraft] = useState<string|null>(null)
  const { currentFirm } = useContext(FirmContext);
  const resourceBasePath = `firm/${currentFirm.instance}/${currentFirm.firm}`
  const templateFieldSchema: ForeignKeySubSchema = {
    type: "object",
    properties: {
      template_id: {
        type: "string",
        title: "Find a template",
        foreignKey: {
          reference: {
            resource: "templates/contracts",
            schema: "ContractTemplate"
          }
        }
      }
    },
  };

  const templateForm = (
    <BaseForm
      schema={templateFieldSchema}
      formData={{template_id: chosenDraft}}
      resourceBasePath={resourceBasePath}
      onChange={(data) => {
        const { template_id } = data;
        setChosenDraft(template_id);
      }}
    >
      &nbsp;
    </BaseForm>
  )

  if (chosenDraft !== null) {
    return (
      <>
        {templateForm}
        <CreateDraftFromTemplate template_id={chosenDraft}/>
      </>
    )
  }

  return (
    <>
      {templateForm}
      <New<Draft> resource={`contracts/drafts`} schemaName={"ContractDraft"} />
    </>
  )
}

const CreateDraftFromTemplate = (props: { template_id: string }) => {
  const { template_id } = props;
  const { currentFirm } = useContext(FirmContext);
  const resourceBasePath = `firm/${currentFirm.instance}/${currentFirm.firm}`
  const resource = "templates/contracts"
  const { data, isLoading } = useOne({
    resource: `${resourceBasePath}/${resource}`,
    id: template_id
  });

  if (isLoading || data === undefined) {
    return <CircularProgress />
  }

  let template = { ...data.data };
  template.provisions = data.data.provisions.map((item: any) => {
    return { provision: {type: "template", provision_template_id: item.provision_template_id} }
  })

  return <New<Draft> resource={`contracts/drafts`} schemaName={"ContractDraft"} defaultValue={ template }/>
}
