import React from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { DeleteForeverRounded } from '@mui/icons-material';

import { DELETE_PERSONAL_SETTING } from '@/modules/@common/acl/constants';

import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  IconButton,
  InlineEditTextField,
  Stack,
} from '@/mui/components';

import styles from './CollapsedContainer.module.scss';

function CollapsedContainer(props) {
  const userPermissions = useSelector(getUserPermissionsSelector);

  return (
    <Accordion expanded={props.expanded} onChange={props.onToggleOpen}>
      <AccordionSummary
        classes={{
          root: styles.AccordionSummary,
          focusVisible: styles.AccordionSummary___focusVisible,
        }}
      >
        <Stack spacing={2} direction="row" alignItems="center" fullWidth justifyContent="space-between">
          <div
            onKeyDown={() => null}
            role="button"
            aria-label="button"
            tabIndex={-1}
            onClick={(event) => event.stopPropagation()}
          >
            <InlineEditTextField
              readOnly={props.disabled}
              value={props.title}
              error={props.hasNameDuplicate}
              helperText={props.hasNameDuplicate ? 'Another rule with that name already exists. Please try again' : ''}
              onApply={(event, value) => props.onTitleChange(value)}
            />
          </div>
          {hasPermission(DELETE_PERSONAL_SETTING, userPermissions) && (
            <div>
              <IconButton
                size="medium"
                color="error"
                className={styles.DeleteIcon}
                onClick={(event, ...args) => {
                  event.stopPropagation();

                  props.onDelete(event, ...args);
                }}
              >
                <DeleteForeverRounded />
              </IconButton>
            </div>
          )}
        </Stack>
      </AccordionSummary>
      <AccordionDetails>{props.children}</AccordionDetails>
    </Accordion>
  );
}

CollapsedContainer.propTypes = {
  expanded: PropTypes.bool.isRequired,
  title: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  disabled: PropTypes.bool.isRequired,
  hasNameDuplicate: PropTypes.bool.isRequired,

  onTitleChange: PropTypes.func.isRequired,
  onDelete: PropTypes.func.isRequired,
  onToggleOpen: PropTypes.func.isRequired,
};

export default CollapsedContainer;
