import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { CheckOutlined, Groups, InfoOutlined, Lock } from '@mui/icons-material';

import { ACCESS_LEVEL_HUB, ACCESS_LEVEL_OPTIONS, ACCESS_LEVEL_PRIVATE } from '../../constants';
import { USER_RULES_SETTINGS as USER_RULES_SETTINGS_ROUTE } from '@/modules/@common/router/constants';

import {
  accessLevelSelector,
  hubOptionsSelector,
  hubsSelector,
  sendHubsNotificationSelector,
} from '../../redux/selectors';
import { getHubOptionsAction, setAction } from '../../redux/slices';
import { changeAccessLevelAction } from '@/modules/editorial/bulkActions/redux/slices';

import useGetSelectedVideo from '@/modules/editorial/bulkActions/hooks/useGetSelectedVideo';
import Title from '../Title/Title';
import {
  Alert,
  Autocomplete,
  Button,
  Checkbox,
  DialogActions,
  DialogContent,
  FormControlLabel,
  Link,
  MenuItem,
  Paper,
  Select,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from '@/mui/components';

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

const ACCESS_LEVEL_INFO = {
  [ACCESS_LEVEL_PRIVATE]: {
    IconInfo: Lock,
    textInfo: 'Only the video owner can access and share the video with other users',
  },
  [ACCESS_LEVEL_HUB]: {
    IconInfo: Groups,
    textInfo: 'Only viewers associated with the hub can watch the video',
  },
};

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

  const [isUserConfirmChangeAccessLevel, setIsUserConfirmChangeAccessLevel] = useState(false);

  const accessLevel = useSelector(accessLevelSelector);
  const hubs = useSelector(hubsSelector);
  const hubOptions = useSelector(hubOptionsSelector);
  const sendHubsNotification = useSelector(sendHubsNotificationSelector);

  const selectedVideo = useGetSelectedVideo();

  const { IconInfo = null, textInfo = '' } = ACCESS_LEVEL_INFO[accessLevel] || {};

  const handleSetAccessLevel = (e) => {
    dispatch(setAction({ accessLevel: e.target.value, sendHubsNotification: false, hubs: [] }));
    setIsUserConfirmChangeAccessLevel(false);
  };
  const handleConfirmChangeAccessLevel = () => setIsUserConfirmChangeAccessLevel(true);
  const handleSetHubs = (_, value) => dispatch(setAction({ hubs: value }));
  const handleSetSendHubsNotification = (e) => dispatch(setAction({ sendHubsNotification: e.target.checked }));
  const handleShare = () => {
    dispatch(changeAccessLevelAction());
    props.onClose();
  };

  return (
    <Paper>
      <Title>
        <Lock htmlColor="text.secondary" fontSize="medium" />
        Access Level
      </Title>
      <DialogContent>
        <Stack spacing={4}>
          <Stack direction="row" justifyContent="center">
            <Stack
              direction="row"
              justifyContent="space-between"
              alignItems="center"
              flexShrink={0}
              className={styles.Label}
            >
              <Typography variant="body2" color="text.primary" fontWeight={400}>
                Select level
              </Typography>
              <Tooltip
                placement="top"
                title="Set the type of access/privacy you wish to apply to this video"
                className={styles.LabelTooltip}
              >
                <InfoOutlined fontSize="small" color="info.main" />
              </Tooltip>
            </Stack>
            <Stack fullWidth direction="row" justifyContent="space-between" alignItems="center" spacing={1}>
              <Select
                className={styles.AccessLevelSelectRoot}
                variant="outlined"
                size="small"
                value={accessLevel}
                displayEmpty
                renderValue={
                  accessLevel !== ''
                    ? undefined
                    : () => (
                        <Typography variant="input-text-small" color="text.secondary" fontWeight={400}>
                          Select Access Level
                        </Typography>
                      )
                }
                onChange={handleSetAccessLevel}
              >
                {ACCESS_LEVEL_OPTIONS.map((option) => (
                  <MenuItem key={option.value} value={option.value}>
                    {option.label}
                  </MenuItem>
                ))}
              </Select>
              <Stack direction="row" fullWidth spacing={1}>
                {IconInfo && <IconInfo fontSize="small" htmlColor="text.secondary" />}
                {textInfo && (
                  <Typography variant="caption" color="text.primary" fontWeight={400}>
                    Only the video owner can access and share the video with other users
                  </Typography>
                )}
              </Stack>
            </Stack>
          </Stack>

          {accessLevel === ACCESS_LEVEL_HUB && (
            <Stack direction="row" justifyContent="center" alignItems="flex-start">
              <Stack
                direction="row"
                justifyContent="space-between"
                alignItems="center"
                flexShrink={0}
                className={styles.Label}
              >
                <Typography variant="body2" color="text.primary" fontWeight={400}>
                  Select Hubs*
                </Typography>
              </Stack>
              <Stack fullWidth>
                <Autocomplete
                  size="small"
                  disableClearable
                  filterSelectedOptions
                  multiple
                  value={hubs}
                  options={hubOptions || []}
                  optionValueKey="id"
                  optionLabelKey="name"
                  renderInput={(params$) => <TextField {...params$} variant="outlined" placeholder="Select Hubs" />}
                  onOpen={() => dispatch(getHubOptionsAction(''))}
                  onInputChange={(_, searchText) => dispatch(getHubOptionsAction(searchText))}
                  onChange={handleSetHubs}
                />
                <FormControlLabel
                  control={
                    <Checkbox
                      size="small"
                      checked={sendHubsNotification}
                      data-id="liveEventCountdown"
                      color="primary"
                      onChange={handleSetSendHubsNotification}
                    />
                  }
                  label={
                    <Typography variant="caption" color="text.primary" fontWeight={400}>
                      Notify users from selected Hubs
                    </Typography>
                  }
                />
              </Stack>
            </Stack>
          )}

          {accessLevel && (
            <Stack>
              <Alert
                className={styles.UserConfirmChangeAccessLevel}
                variant="outlined"
                severity="info"
                action={
                  <>
                    {!isUserConfirmChangeAccessLevel && (
                      <Button
                        variant="text"
                        size="medium"
                        color="primary"
                        shape="rounded"
                        onClick={handleConfirmChangeAccessLevel}
                      >
                        Got it
                      </Button>
                    )}
                    {isUserConfirmChangeAccessLevel && <CheckOutlined fontSize="medium" htmlColor="success.main" />}
                  </>
                }
              >
                {accessLevel === ACCESS_LEVEL_PRIVATE && (
                  <>You are attempting to revoke all Hub access to {selectedVideo} videos.</>
                )}
                {accessLevel === ACCESS_LEVEL_HUB && (
                  <>
                    You are attempting to expand access to {selectedVideo} videos. Existing viewers will not be
                    affected.
                  </>
                )}
              </Alert>
            </Stack>
          )}
        </Stack>
      </DialogContent>
      <DialogActions>
        <Stack fullWidth direction="row" justifyContent="space-between">
          <Typography variant="caption" color="text.secondary" fontWeight={400}>
            To share videos automatically go to &nbsp;
            <Link label="Personal Settings" href={USER_RULES_SETTINGS_ROUTE.path} target="_blank">
              Personal Settings
            </Link>
          </Typography>
          <Stack direction="row" spacing={2}>
            <Button size="small" variant="outlined" color="primary" onClick={props.onClose}>
              Cancel
            </Button>

            <Button
              size="small"
              variant="contained"
              color="primary"
              disabled={!isUserConfirmChangeAccessLevel || (accessLevel === ACCESS_LEVEL_HUB && !hubs.length)}
              onClick={handleShare}
            >
              Share
            </Button>
          </Stack>
        </Stack>
      </DialogActions>
    </Paper>
  );
}

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

export default ChangeAccessLevel;
