import { useContext } from "react";
import { Route, Routes, useParams } from "react-router";
import { useOne, useTranslation } from "@refinedev/core";
import { DeleteButton } from "@refinedev/mui";
import { CircularProgress, Stack } from "@mui/material";
import { CrudForm } from "../../lib/crud/components/crud-form";
import { FirmContext } from "../../contexts/FirmContext";
import List from "./base-page/List";
import Cartouche from "../../components/Cartouche";

export type Contract = {
  id: string,
  label: string
}

export const ContractRoutes = () => {
  return (
    <Routes>
      <Route index element={ <ListContract /> } />
      <Route path="/edit/:record_id" element={ <EditContract /> } />
    </Routes>
  );
}

const ListContract = () => {
  const columns = [
    { field: "label",  column: { flex: 1 }},
    { field: "status",  column: { width: 160 }},
    { field: "updated_at", column: { width: 160 }},
  ];
  return <List<Contract> resource={`contracts`} schemaName={"Contract"} columns={columns} />
}

const EditContract = () => {
  const { currentFirm } = useContext(FirmContext);
  const { translate: t } = useTranslation();
  const resourceBasePath = `firm/${currentFirm.instance}/${currentFirm.firm}`
  const { record_id } = useParams();

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

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

  const record = data.data;
  return (
    <>
      <h2>{record.label}</h2>
      <Cartouche record={record}/>
      <CrudForm
        resourceBasePath={resourceBasePath}
        schemaName={"Contract"}
        uiSchema={{"ui:readonly": true }}
        record={record}
        card={true}
      >
        <Stack
          direction="row"
          spacing={2}
          sx={{
            justifyContent: "flex-end",
            alignItems: "center",
          }}>
          { record.status == "published" && (<DeleteButton variant="contained" size="large" color="error" recordItemId={record_id}/>) }
        </Stack>
      </CrudForm>
    </>
  )
}