import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
} from '@material-ui/core';
import { Role } from 'features/user/userSlice';
import React, { useState } from 'react';

import { AllUsers, UpdateUser } from '.';
import { availableRoles } from 'api/configuration';

interface EditUsersModal {
  usersToEdit: AllUsers;
  setUsersToEdit: (users: AllUsers) => void;
  updateUser: UpdateUser;
}

export default function EditUsersModal({
  usersToEdit,
  setUsersToEdit,
  updateUser,
}: EditUsersModal) {
  const [role, setRole] = useState<Role | ''>('');
  const handleAddRemove = (action: 'add' | 'remove') => {
    if (role === '') return setUsersToEdit([]);
    const updatedUsers = usersToEdit
      .filter(
        ({ preferences }) =>
          (preferences.roles.includes(role) && action === 'remove') ||
          (!preferences.roles.includes(role) && action === 'add'),
      )
      .map(({ preferences, ...user }) => {
        return {
          ...user,
          preferences: {
            ...preferences,
            roles:
              action === 'remove'
                ? preferences.roles.filter(rl => rl !== role)
                : [...preferences.roles, role],
          },
        };
      });
    updateUser(updatedUsers);
    setUsersToEdit([]);
  };
  const handleClose = () => setUsersToEdit([]);
  return (
    <Dialog
      onClose={handleClose}
      open={usersToEdit.length > 0}
      aria-labelledby="edit-users"
    >
      <DialogTitle id="edit-users">Add/Remove Groups</DialogTitle>
      <DialogContent>
        <FormControl fullWidth>
          <InputLabel id="edit-users-role-select-label">Role</InputLabel>
          <Select
            labelId="edit-users-role-select-label"
            id="edit-users-role-select"
            value={role}
            onChange={({ target: { value } }) => setRole(value as Role)}
            fullWidth
          >
            {availableRoles.map(role => (
              <MenuItem key={role} value={role}>
                {role}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </DialogContent>
      <DialogActions>
        <Button color="primary" onClick={() => handleAddRemove('add')}>
          Add
        </Button>
        <Button color="primary" onClick={() => handleAddRemove('remove')}>
          Remove
        </Button>
      </DialogActions>
    </Dialog>
  );
}
