import { useTableFormIteratorItem } from './TableFormIteratorItemContext';
import { Button, Dialog } from '@mui/material';
import React from 'react';
import { EditContextProvider, SaveHandler, useArrayInput, useTranslate } from 'react-admin';

function EditButton(props: any) {
  const { children } = props;
  const { item, index } = useTableFormIteratorItem();
  const [open, setOpen] = React.useState(false);
  const { update } = useArrayInput();
  const translate = useTranslate();

  const handleSave: SaveHandler<any> = React.useCallback(
    (data) => {
      setOpen(false);
      update(index, data);
      return Promise.resolve();
    },
    [index, update]
  );

  return (
    <>
      <Button color="primary" onClick={() => setOpen(true)} sx={{ justifyContent: 'flex-start' }}>
        {translate('ra.action.edit')}
      </Button>
      <Dialog open={open} onClose={() => setOpen(false)} maxWidth="xs" fullWidth>
        <EditContextProvider
          // @ts-ignore
          value={{
            record: item,
            save: handleSave
          }}
        >
          {children}
        </EditContextProvider>
      </Dialog>
    </>
  );
}

export { EditButton };
