import { ReactNode, cloneElement, useCallback } from 'react';
import { Box, Button } from '@mui/material';
import { Toolbar as RaToolbar, ToolbarProps } from '@/components/ra-forms/Toolbar';
import { SaveButton } from 'react-admin';
import { useTranslate } from 'ra-core';
import { useFormContext } from 'react-hook-form';
import { useWizardFormContext } from './Provider';

interface WizardToolbarProps extends ToolbarProps {
  cancelButton?: ReactNode;
}

/**
 * Toolbar component for the WizardForm.
 *
 * This component renders a toolbar with navigation buttons for a multi-step form.
 * It includes buttons to navigate to the previous and next steps, as well as a cancel button.
 *
 * @param {WizardToolbarProps} props - The properties for the Toolbar component.
 * @param {React.ReactElement} props.cancelButton - An optional cancel button element.
 * @param {object} props.toolbarProps - Additional properties to pass to the RaToolbar component.
 *
 * @returns {JSX.Element} The rendered Toolbar component.
 */
function Toolbar({ cancelButton, ...props }: WizardToolbarProps) {
  const { hasNextStep, hasPreviousStep, goToNextStep, goToPreviousStep } = useWizardFormContext();
  const translate = useTranslate();
  const { handleSubmit } = useFormContext();
  const onSubmit = useCallback(() => {
    goToNextStep();
  }, [goToNextStep]);

  return (
    <RaToolbar {...props}>
      <Box sx={{ '& .MuiButtonBase-root': { ml: 0 } }}>
        {
          //@ts-ignore
          cancelButton ? cloneElement(cancelButton) : null
        }
      </Box>
      <Box sx={{ flex: '1 1 auto' }} />
      {hasPreviousStep() && (
        <Button variant="text" color="primary" onClick={goToPreviousStep}>
          {translate('ra.action.back')}
        </Button>
      )}
      {hasNextStep() ? (
        <Button variant="contained" color="primary" onClick={handleSubmit(onSubmit)}>
          {translate('ra.action.next')}
        </Button>
      ) : (
        <SaveButton />
      )}
    </RaToolbar>
  );
}

export { Toolbar };
