import { useThemeConfig } from '@/components/Layout/ThemeProvider';
import { Grid } from '@mui/material';
import { styled } from '@mui/material/styles';
import _ from 'lodash';
import { Form, FormProps } from 'react-admin';

type IBaseFormProps = FormProps & {
  spacing?: number;
};

const StyledGrid = styled(Grid, {
  name: 'LongFormView',
  slot: 'Root'
})(({ theme }) => ({
  // This style must be applied only to root toolbars used to save data in the form.
  // Other toolbars must be handled outside this rule.
  '& .MuiToolbar-root.RaToolbar-desktopToolbar': {
    marginLeft: `-${theme.spacing(3)}`,
    marginRight: `-${theme.spacing(3)}`,
    marginBottom: `-${theme.spacing(2)}`,
    paddingTop: theme.spacing(2.5),
    paddingBottom: theme.spacing(2.5),
    [theme.breakpoints.down('sm')]: {
      width: 'auto !important',
      marginRight: 0
    }
  },
  '& .RaToolbar-mobileToolbar': {
    paddingTop: `${theme.spacing(2.5)} !important`,
    paddingLeft: '0 !important',
    paddingRight: '0 !important',
    paddingBottom: '0 !important'
  },
  '& form > .MuiToolbar-root': {
    // This is really important: this rule is used to insert forms inside other forms, avoiding
    // the toolbar of the inner form to receive the styles of the previous rule (which generates a strange padding).
    margin: 0,
    marginRight: `-${theme.spacing(0.5)}`,
    [theme.breakpoints.down('sm')]: {
      marginRight: theme.spacing(0.5)
    }
  }
}));

function BaseForm(props: IBaseFormProps) {
  const { spacing: themeSpacing } = useThemeConfig();
  const { spacing = themeSpacing } = props;
  const formProps = _.omit(props, ['spacing']);

  return (
    <Form {...formProps} className="LongFormView">
      <StyledGrid container spacing={spacing * 2}>
        {props.children}
      </StyledGrid>
    </Form>
  );
}

export { BaseForm };

export type { IBaseFormProps };
