import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { DeleteRounded } from '@mui/icons-material';

import { Autocomplete, Divider, IconButton, Paper, Stack, TextField, Typography, UserAvatar } from '@/mui/components';

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

function UsersAutocomplete(props) {
  const [inputValue, setInputValue] = useState('');

  const handleDeleteUser = (userId) => {
    const users = props.users.filter((user) => user.id !== userId);
    props.onChange(users);
  };

  const options = props.users.length
    ? props.options?.filter((option) => props.users.every((user) => user.id !== option.id))
    : props.options;

  return (
    <Stack spacing={2} fullWidth>
      <Autocomplete
        fullWidth
        multiple
        disableClearable
        size="small"
        popupIcon={null}
        options={options || []}
        loading={!options}
        value={[]}
        inputValue={inputValue}
        disabled={props.disabled}
        loadingText={
          <Typography variant="body2" color="text.secondary" fontWeight={400}>
            Loading...
          </Typography>
        }
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="Select"
            onChange={({ target }) => {
              setInputValue(target.value);
              props.onGetOptions(target.value);
            }}
          />
        )}
        renderOption={(optionProps, option) => (
          <Stack spacing={2} direction="row" alignItems="center" fullWidth {...optionProps}>
            <UserAvatar id={option.id} firstName={option.firstName} lastName={option.lastName} />
            <Stack spacing={0} fullWidth>
              <Typography variant="body2" color="text.primary" fontWeight={400}>
                {`${option.firstName} ${option.lastName}`}
              </Typography>
              <Typography variant="body2" color="text.secondary" fontWeight={400}>
                {option.email}
              </Typography>
            </Stack>
          </Stack>
        )}
        getOptionLabel={(option) => `${option.firstName} ${option.lastName} ${option.email}`}
        onOpen={() => props.onGetOptions(inputValue)}
        onChange={(e, value) => {
          props.onChange([].concat(props.users, value));
          setInputValue('');
        }}
      />
      {!!props.users?.length && (
        <Paper elevation={2} className={styles.Users}>
          <Stack spacing={1} fullWidth divider={<Divider flexItem />}>
            {props.users?.map((user) => (
              <Stack spacing={2} key={user.id} direction="row" fullWidth alignItems="center">
                <UserAvatar size="small" id={user.id} firstName={user.firstName} lastName={user.lastName} />
                <Stack className={styles.Data} fullWidth>
                  <Typography component="div" variant="caption" color="text.primary" fontWeight={400} noWrap>
                    {`${user?.firstName ?? ''} ${user?.lastName ?? ''}`}
                  </Typography>
                  <Typography component="div" variant="caption" color="text.secondary" noWrap fontWeight={400}>
                    {user.email}
                  </Typography>
                </Stack>
                <Typography variant="caption" color="text.secondary" fontWeight={500}>
                  Viewer
                </Typography>
                <IconButton
                  size="xSmall"
                  color="neutral"
                  disabled={props.disabled}
                  onClick={() => handleDeleteUser(user.id)}
                >
                  <DeleteRounded />
                </IconButton>
              </Stack>
            ))}
          </Stack>
        </Paper>
      )}
    </Stack>
  );
}

UsersAutocomplete.propTypes = {
  options: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  users: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  disabled: PropTypes.bool.isRequired,
  onGetOptions: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default UsersAutocomplete;
