import { Box, Checkbox, FormControlLabel, MenuItem, OutlinedInput, Select, Typography } from '@mui/material';
import { ExpandMore as ExpandMoreIcon } from '@mui/icons-material';
import { makeStyles } from 'tss-react/mui';

import type { SectionClasses } from '../HostManagement';
import type { GroupCleanup, HostGroup } from '../store/managementSlice';

const useStyles = makeStyles()(theme => ({
  select: {
    marginLeft: theme.spacing(4),
    minWidth: 220,
    '& .MuiSelect-root.MuiOutlinedInput-root': {
      width: 172,
      height: 32
    },
    '& .MuiSelect-icon': {
      right: 8
    }
  }
}));

type Props = {
  value: GroupCleanup;
  groups: HostGroup[];
  onChange: (value: GroupCleanup) => void;
  classes: SectionClasses;
};

export const GroupBasedCleanupSection = ({ value, groups, onChange, classes }: Props) => {
  const { classes: ownClasses, cx } = useStyles();
  return (
    <Box>
      <Typography component="h3" variant="h6" sx={{ fontWeight: 500, fontSize: 16, mb: 2 }}>
        Group-based cleanup
      </Typography>
      <FormControlLabel
        className={classes.formLabel}
        control={
          <Checkbox
            checked={value.enabled}
            color="primary"
            onChange={e => onChange({ ...value, enabled: e.target.checked })}
          />
        }
        label="Automatically delete hosts in shared group"
      />
      <Box className={ownClasses.select}>
        <Select
          displayEmpty
          input={<OutlinedInput />}
          IconComponent={ExpandMoreIcon}
          disabled={!value.enabled}
          value={value.groupId}
          onChange={e => onChange({ ...value, groupId: Number(e.target.value) || null })}
        >
          <MenuItem value="" disabled>
            Select group
          </MenuItem>
          {groups.map(group => (
            <MenuItem key={group.id} value={group.id}>
              {group.name}
            </MenuItem>
          ))}
        </Select>
      </Box>
      <FormControlLabel
        className={cx(classes.nested, classes.formLabel)}
        control={
          <Checkbox
            checked={value.completelyClear}
            color="primary"
            disabled={!value.enabled}
            onChange={e => onChange({ ...value, completelyClear: e.target.checked })}
          />
        }
        label="Completely clear host entry, allowing it to reappear if it starts reporting."
      />
    </Box>
  );
};

export default GroupBasedCleanupSection;
