import { ActionsMenu } from '@/components/ActionsMenu';
import { MainCard } from '@/components/MainCard';
import { Toolbar } from '@/components/ra-forms/Toolbar';
import { useResourceTitle } from '@/hooks';
import { styled, useTheme } from '@mui/system';
import {
  SimpleForm as RaSimpleForm,
  SimpleFormProps as RaSimpleFormProps,
  SaveButton,
  useRecordContext
} from 'react-admin';
import { DeleteWithConfirmButton } from '@/components/ra-buttons';

const StyledSimpleForm = styled(RaSimpleForm, { slot: 'Root' })(({ theme }: { theme: any }) => ({
  [theme.breakpoints.down('sm')]: {
    paddingBottom: `${theme.spacing(2.5)}`
  }
}));

function SimpleForm({
  title,
  modal = false,
  // @ts-ignore
  content = false,
  subheader = null,
  toolbar = (
    <Toolbar>
      <SaveButton type="button" />
    </Toolbar>
  ),
  secondary = (
    <ActionsMenu>
      <DeleteWithConfirmButton />
    </ActionsMenu>
  ),
  sx,
  ...props
}: SimpleFormProps): JSX.Element {
  const cardTitle = useResourceTitle(title);
  const record = useRecordContext();
  const theme = useTheme();
  return (
    // @ts-ignore
    <MainCard
      content={content}
      title={cardTitle}
      subheader={subheader}
      secondary={record?.id ? secondary : null}
      sx={{
        ...sx,
        '& .MuiToolbar-root': {
          paddingLeft: theme.spacing(2.5),
          paddingRight: theme.spacing(2.5),
          paddingBottom: theme.spacing(2.5),
          paddingTop: modal ? theme.spacing(2.5) : 0,
          borderTop: modal ? `1px solid ${theme.palette.divider}` : undefined
        }
      }}
      border={!modal}
      divider
    >
      {/* @ts-ignore */}
      <StyledSimpleForm toolbar={toolbar} {...props} />
    </MainCard>
  );
}

type SimpleFormProps = RaSimpleFormProps & {
  modal?: boolean;
  content?: boolean;
  subheader?: string | React.ReactNode;
  title?: string | React.ReactNode;
  secondary?: string | React.ReactNode;
};

export { SimpleForm };
export type { SimpleFormProps };
