"use client";

import { FC, useEffect } from "react";
import { Grid } from "@mui/material";
import { useRouter } from "next/navigation";
import { Button, Dialog } from "ui";

interface EditProps {
  title: string;
  entity: string;
  formAction: any;
  formState: any;
  children: any;
}

export const Edit: FC<EditProps> = ({
  title,
  entity,
  formState,
  formAction,
  children,
}) => {
  const router = useRouter();

  useEffect(() => {
    if (formState.success) {
      router.push(`/${entity}`);
    }
  }, [formState.success, router]);

  return (
    <Dialog
      open
      title={title}
      formAction={formAction}
      onClose={() => router.push(`/${entity}`)}
      buttons={
        <Grid container justifyContent="space-between">
          <Grid item>
            <Button
              text="Cancel"
              kind="secondary"
              onClick={() => router.push(`/${entity}`)}
            />
          </Grid>
          <Grid item>
            <Button text="Save" kind="primary" type="submit" />
          </Grid>
        </Grid>
      }
    >
      {children}
    </Dialog>
  );
};
