import { UiSchema } from "@rjsf/utils";
import { useContext } from "react";
import { useParams, Navigate } from "react-router";
import { Button, CircularProgress } from "@mui/material";
import Stack from "@mui/material/Stack";
import SaveIcon from '@mui/icons-material/Save';
import { useForm, useTranslation } from "@refinedev/core";
import { DeleteButton } from "@refinedev/mui";
import { FirmContext } from "../../../contexts/FirmContext";
import { CrudForm } from "../../../lib/crud/components/crud-form";
import Cartouche from "../../../components/Cartouche";

type EditProps = {
  resource: string,
  schemaName: string,
  uiSchema?: UiSchema,
}

const Edit = <T,>(props: EditProps) => {
  const { schemaName, resource, uiSchema } = props;
  const { currentFirm } = useContext(FirmContext);
  const { translate: t } = useTranslation();
  const resourceBasePath = `firm/${currentFirm.instance}/${currentFirm.firm}`
  const { record_id } = useParams();

  const { onFinish, query, formLoading } = useForm({
    resource: `${resourceBasePath}/${resource}`,
    action: "edit",
    redirect: "show",
    id: record_id,
  });

  if (formLoading) {
    return <CircularProgress />
  }

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

  const record = query.data.data;
  return (
    <>
      <h2>{record.label}</h2>
      <Cartouche record={record}/>
      <CrudForm
        resourceBasePath={resourceBasePath}
        schemaName={schemaName}
        uiSchema={uiSchema}
        record={record}
        onSubmit={(data: any) => onFinish(data)}
      >
        <Stack
          direction="row"
          spacing={2}
          sx={{
            justifyContent: "space-between",
            alignItems: "center",
          }}>
          <Button type='submit' variant="contained" size="large"><SaveIcon />{t("buttons.save")}</Button>
          <DeleteButton variant="contained" size="large" color="error" recordItemId={record_id}/>
        </Stack>
      </CrudForm>
    </>
  )
}

export default Edit;
