import { AddTableRow } from './AddTableRow';
import { Dialog } from '@mui/material';
import { CreateContextProvider, SaveHandler } from 'ra-core';
import React from 'react';
import { useArrayInput } from 'react-admin';

interface CreateButtonProps {
  label: string;
  disableAdd?: boolean;
  inset?: boolean;
  source?: string;
  template?: any;
  children: React.ReactNode;
}

function TableCreateButton(props: CreateButtonProps): JSX.Element {
  const { label, disableAdd, inset, source, template } = props;
  const [open, setOpen] = React.useState(false);
  const { append } = useArrayInput();

  const toggleOpen = React.useCallback(() => {
    setOpen((prev) => !prev);
  }, [setOpen]);

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

  return (
    <>
      {React.cloneElement(<AddTableRow />, {
        label,
        source,
        disableAdd,
        template,
        onClick: toggleOpen,
        inset
      })}
      <Dialog open={open} onClose={toggleOpen} maxWidth="xs">
        <CreateContextProvider
          // @ts-ignore
          value={{
            save: handleSave as SaveHandler<any>
          }}
        >
          {props.children}
        </CreateContextProvider>
      </Dialog>
    </>
  );
}

export { TableCreateButton };
