import PropTypes from 'prop-types';
import ActionDelete from '@mui/icons-material/Delete';
import clsx from 'clsx';
import inflection from 'inflection';
import { RaRecord, useDeleteWithConfirmController, useRecordContext, useResourceContext, useTranslate } from 'ra-core';
import { Button } from './Button';
import { Confirm, DeleteWithConfirmButtonProps as RaDeleteWithConfirmButtonProps } from 'ra-ui-materialui';
import { Box, SxProps, Typography, useTheme } from '@mui/material';
import { DeleteFilled } from '@ant-design/icons';
import { useCallback } from 'react';

type DeleteWithConfirmButtonProps<RecordType extends RaRecord = RaRecord> =
  RaDeleteWithConfirmButtonProps<RecordType> & {
    dialogSx?: SxProps;
    /**
     * @deprecated confirmTitle prop is deprecated, please use confirmContent instead.
     */
    confirmTitle?: React.ReactNode;
    /**
     * onConfirm {callback} is used to handle a custom delete action when user confirms the deletion.
     */
    onConfirm?: () => void;
  };

function DeleteWithConfirmButton<RecordType extends RaRecord = any>(
  props: DeleteWithConfirmButtonProps<RecordType>
): JSX.Element {
  const {
    className,
    confirmTitle,
    confirmContent,
    confirmColor = 'primary',
    color = 'error',
    dialogSx,
    icon = <ActionDelete />,
    label = 'ra.action.delete',
    mutationMode = 'pessimistic',
    mutationOptions,
    onClick,
    redirect = 'list',
    translateOptions = {},
    onConfirm,
    ...rest
  } = props;
  const translate = useTranslate();
  const record = useRecordContext(props);
  const resource = useResourceContext(props);
  const theme = useTheme();

  const { open, isLoading, handleDialogOpen, handleDialogClose, handleDelete } = useDeleteWithConfirmController({
    record,
    redirect,
    mutationMode,
    onClick,
    mutationOptions,
    resource
  });

  const handleOnConfirm = useCallback(
    (event: any) => {
      if (onConfirm) {
        onConfirm();
      } else {
        handleDelete(event);
      }
    },
    [handleDelete, onConfirm]
  );

  return (
    <>
      <Button
        onClick={handleDialogOpen}
        label={label}
        className={clsx('ra-delete-button', className)}
        key="button"
        color={color}
        {...rest}
      >
        {icon}
      </Button>
      <Confirm
        isOpen={open}
        loading={isLoading}
        sx={
          dialogSx || {
            '& .MuiPaper-root': {
              p: 2
            },
            '& .MuiDialogActions-root': {
              display: 'flex',
              justifyContent: 'space-between',
              width: '100%',
              '& .RaConfirm-confirmPrimary': {
                backgroundColor: theme.palette.primary.main,
                color: theme.palette.primary.contrastText,
                ml: 2,
                '&:hover': {
                  backgroundColor: theme.palette.primary.dark
                },
                '&.Mui-disabled': {
                  backgroundColor: theme.palette.action.disabled,
                  color: theme.palette.primary.contrastText,
                  outline: 'none',
                  boxShadow: 'none',
                  border: `1px solid ${theme.palette.action.disabled}`
                }
              },
              '& .MuiButtonBase-root': {
                width: '50%',
                border: `1px solid ${theme.palette.action.disabled}`
              },
              '& .MuiButton-icon': {
                display: 'none'
              }
            }
          }
        }
        title={
          confirmTitle ? (
            typeof confirmTitle === 'string' ? (
              translate(confirmTitle)
            ) : (
              confirmTitle
            )
          ) : (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              <Box
                sx={{
                  color: 'primary.main',
                  fontSize: '28px',
                  borderRadius: '50%',
                  backgroundColor: 'primary.lighter',
                  width: '56px',
                  height: '56px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                <DeleteFilled />
              </Box>
            </Box>
          )
        }
        content={
          <Typography maxWidth="300px" variant="h4" align="center">
            {confirmContent ||
              translate('ra.message.delete_content', {
                _: 'ra.message.delete_content',
                name: translate(`resources.${resource}.forcedCaseName`, {
                  smart_count: 1,
                  _: inflection.humanize(
                    translate(`resources.${resource}.name`, {
                      smart_count: 1,
                      _: inflection.singularize(resource)
                    }),
                    true
                  )
                }),
                id: record?.id
              })}
          </Typography>
        }
        confirmColor={confirmColor}
        translateOptions={{
          name: translate(`resources.${resource}.forcedCaseName`, {
            smart_count: 1,
            _: inflection.humanize(
              translate(`resources.${resource}.name`, {
                smart_count: 1,
                _: inflection.singularize(resource)
              }),
              true
            )
          }),
          id: record?.id,
          ...translateOptions
        }}
        onConfirm={handleOnConfirm}
        onClose={handleDialogClose}
      />
    </>
  );
}

DeleteWithConfirmButton.propTypes = {
  basePath: PropTypes.string,
  className: PropTypes.string,
  confirmColor: PropTypes.string,
  confirmContent: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  confirmTitle: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  icon: PropTypes.element,
  label: PropTypes.string,
  mutationMode: PropTypes.oneOf(['pessimistic', 'optimistic', 'undoable']),
  onClick: PropTypes.func,
  record: PropTypes.any,
  redirect: PropTypes.oneOfType([PropTypes.string, PropTypes.bool, PropTypes.func]),
  resource: PropTypes.string,
  translateOptions: PropTypes.object
};

export { DeleteWithConfirmButton };
