import { Navigate, Route, Routes, useParams } from "react-router";
import { CircularProgress } from "@mui/material";
import React, { useContext, useState } from "react";
import { useOne, useTranslation } 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";
import { Contract } from "./ContractRoutes";
import dayjs from "dayjs";

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", column: { flex: 1 }},
  ];
  return <List<Draft> resource={`contracts/drafts`} columns={columns} schemaName={"Contract"} />
}

const EditDraft = () => {
  const { currentFirm } = useContext(FirmContext);
  const { record_id } = useParams();
  const resourceBasePath = `firm/${currentFirm.instance}/${currentFirm.firm}`

  const { data, isLoading } = useOne({
    resource: `${resourceBasePath}/contracts/drafts`,
    id: record_id
  })

  if (isLoading) {
    return <CircularProgress />
  }

  if (!data?.data) {
    return <Navigate to="../" />
  }

  const draft = data?.data
  const readOnly = draft.status === "published";

  const uiSchema = {
    "ui:readonly":  readOnly
  }

  return (
    <>
      <Edit<Draft> resource={"contracts/drafts"} schemaName={"ContractDraft"} uiSchema={uiSchema} />
      <ContractCreate draft={draft}></ContractCreate>
    </>
  )
}

const ContractCreate = (props: { draft: any}) => {
  const { translate: t } = useTranslation();
  const { draft } = props;

  if (draft.status === "published") {
    return <h4>{t("resource.draft.already_published") }</h4>
  }
  if (draft.status === "in_progress") {
    return (
      <>
        <h4>{ t("resource.draft.todo") + ":" }</h4>
        <ul>{ draft.todo.map((item: any) => <li>{ item }</li>) }</ul>
      </>
    )
  }
  return <New<Contract>
    resource={"contracts"}
    schemaName={"Contract"}
    defaultValue={{
      date: dayjs().format("YYYY-MM-DD"),
      location: "Los Santos, SA",
      draft_id: draft.id
    }}
    uiSchema={{ draft_id: { 'ui:widget': 'hidden' } }}
  />
}

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 }/>
}
