import React from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { ArrowBack, PersonAddAlt1 } from '@mui/icons-material';

import { isUserShareModeSelector, messageSelector, userOptionsSelector, usersSelector } from '../../redux/selectors';
import { getUserOptionsAction, setAction } from '../../redux/slices';
import { shareWithUsersAction } from '@/modules/editorial/bulkActions/redux/slices';

import useGetSelectedVideo from '@/modules/editorial/bulkActions/hooks/useGetSelectedVideo';
import Title from '../Title/Title';
import {
  Autocomplete,
  Button,
  DialogActions,
  DialogContent,
  Paper,
  Stack,
  TextField,
  Typography,
  UserAvatar,
} from '@/mui/components';

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

function ShareToUsers(props) {
  const dispatch = useDispatch();

  const isUserShareMode = useSelector(isUserShareModeSelector);
  const users = useSelector(usersSelector);
  const userOptions = useSelector(userOptionsSelector);
  const message = useSelector(messageSelector);

  const selectedVideo = useGetSelectedVideo();

  const handleSetUsers = (_, value) => {
    const payload = { users: value };
    if (value.length > 0) {
      payload.isUserShareMode = true;
    }
    dispatch(setAction(payload));
  };

  const handleCancelUserShareMode = () => dispatch(setAction({ isUserShareMode: false, users: [], message: '' }));

  const handleSetMessage = (e) => dispatch(setAction({ message: e.target.value }));

  const handleShare = () => {
    dispatch(shareWithUsersAction());
    props.onClose();
  };

  return (
    <Paper>
      <Title onClose={props.onClose}>
        {!isUserShareMode && <PersonAddAlt1 htmlColor="text.secondary" fontSize="medium" />}
        {isUserShareMode && (
          <ArrowBack htmlColor="text.secondary" fontSize="medium" onClick={handleCancelUserShareMode} />
        )}
        <span>{`Share ${selectedVideo} Video${selectedVideo > 1 ? 's' : ''}`}</span>
      </Title>
      <DialogContent>
        <Stack spacing={4}>
          <Stack direction="row" alignItems="flex-start" spacing={2}>
            <Stack direction="row" alignItems="flex-start" flexShrink={0} className={styles.Label}>
              <Typography variant="body2" color="text.primary" fontWeight={400}>
                Share with
              </Typography>
            </Stack>
            <Stack fullWidth>
              <Autocomplete
                size="small"
                disableClearable
                filterSelectedOptions
                multiple
                value={users}
                getOptionLabel={(option) => `${option.firstName} ${option.lastName}`}
                options={userOptions || []}
                optionValueKey="email"
                renderInput={(params$) => <TextField {...params$} variant="outlined" placeholder="Select Users" />}
                renderOption={(optionProps, option) => (
                  <Stack spacing={2} direction="row" alignItems="center" fullWidth {...optionProps} key={option.id}>
                    <UserAvatar id={option.id} firstName={option.firstName} lastName={option.lastName} />
                    <Stack spacing={1} 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>
                )}
                onOpen={() => dispatch(getUserOptionsAction(''))}
                onInputChange={(_, searchText) => dispatch(getUserOptionsAction(searchText))}
                onChange={handleSetUsers}
              />
            </Stack>
          </Stack>
          {isUserShareMode && (
            <Stack spacing={2} direction="row" alignItems="flex-start" fullWidth>
              <Stack direction="row" alignItems="flex-start" flexShrink={0} className={styles.Label}>
                <Typography variant="body2" color="text.primary" fontWeight={400}>
                  Message (optional)
                </Typography>
              </Stack>
              <Stack fullWidth>
                <TextField
                  value={message}
                  fullWidth
                  multiline
                  size="small"
                  onChange={handleSetMessage}
                  placeholder="Message"
                  minRows={2}
                  inputProps={{ maxLength: 3000 }}
                />
              </Stack>
            </Stack>
          )}
        </Stack>
      </DialogContent>
      {isUserShareMode && (
        <DialogActions>
          <Button size="small" variant="outlined" color="primary" onClick={props.onClose}>
            Cancel
          </Button>
          <Button size="small" variant="contained" color="primary" onClick={handleShare}>
            Share
          </Button>
        </DialogActions>
      )}
    </Paper>
  );
}

ShareToUsers.propTypes = {
  onClose: PropTypes.func.isRequired,
};

export default ShareToUsers;
