import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import {
  CloudUploadOutlined,
  ContentCutRounded,
  DeleteForever,
  EnergySavingsLeafRounded,
  Inventory,
  MoreVertRounded,
  SendRounded,
  StickyNote2Rounded,
} from '@mui/icons-material';

import { PCN_GET_DESTINATIONS, VIDEO_ADMIN } from '@/modules/@common/acl/constants';
import { JOB_STATUS_PROCESSING, JOB_STATUS_STARTED } from '@/modules/editorial/constants/monitoringJobs';

import { openAction } from '../../../common/components/trimVideo/redux/slices';
import { checkCcFileStateMonitoringIsActiveSelector as ccFileIsMonitoringActiveSelector } from '@/modules/@common/ccFiles/redux/selectors';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { monitoringJobsSelector } from '@/modules/editorial/editorialSearch/redux/selectors';
import { isChaptersMonitoringActive as chaptersIsMonitoringActiveSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';
import { openVideoVersionUploadAction } from '@/modules/uploaderNew/redux/slices';

import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  IconButton,
  Menu,
  MenuItem,
  Stack,
  Switch,
  TextField,
  Typography,
} from '@/mui/components';

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

function MenuComponent({ evergreen = false, notes = null, shouldOpenVideoMenuImmediately = false, ...props }) {
  const dispatch = useDispatch();
  const buttonRef = useRef(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);
  const [isNotesOpen, setNotesOpen] = useState(false);
  const [notes$, setNotes$] = useState(notes);
  const [isOpenPermanentDelete, setIsOpenPermanentDelete] = useState(false);

  const userPermissions = useSelector(getUserPermissionsSelector);

  const monitoring = useSelector(monitoringJobsSelector);
  const chaptersIsMonitoringActive = useSelector(chaptersIsMonitoringActiveSelector);
  const ccFileIsMonitoringActive = useSelector(ccFileIsMonitoringActiveSelector);

  const hasActiveMonitoringJobs = monitoring.some((monitoringJob) =>
    [JOB_STATUS_STARTED, JOB_STATUS_PROCESSING].includes(monitoringJob?.state),
  );

  const shouldDisableUploadVersion = hasActiveMonitoringJobs || chaptersIsMonitoringActive || ccFileIsMonitoringActive;

  const closeMenu = () => setAnchorEl(null);

  useEffect(() => {
    setAnchorEl(shouldOpenVideoMenuImmediately ? buttonRef.current : null);

    return () => {
      setAnchorEl(null);
    };
  }, [shouldOpenVideoMenuImmediately]);

  return (
    <>
      <IconButton ref={buttonRef} size="xSmall" color="neutral" onClick={(event) => setAnchorEl(event.currentTarget)}>
        <MoreVertRounded />
      </IconButton>
      {open && (
        <Menu
          anchorEl={anchorEl}
          open={open}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
          onClose={closeMenu}
        >
          {props.canEditVideo && (
            <MenuItem
              data-id="edit-video"
              onClick={() => {
                dispatch(openAction());
                closeMenu(null);
              }}
            >
              <ContentCutRounded htmlColor="info.dark" fontSize="medium" />
              Edit Video
            </MenuItem>
          )}
          {hasPermission(PCN_GET_DESTINATIONS, userPermissions) && (
            <MenuItem
              data-id="publish"
              onClick={() => {
                props.onPublish(true);
                closeMenu(null);
              }}
            >
              <SendRounded htmlColor="info.dark" fontSize="medium" />
              Publish
            </MenuItem>
          )}
          <MenuItem data-id="evergreen" onClick={() => null}>
            <EnergySavingsLeafRounded htmlColor="info.dark" fontSize="medium" />
            Evergreen
            <div className={styles.RightPart}>
              <Switch
                size="small"
                checked={evergreen}
                onClick={() => props.onEvergreenSet(!evergreen)}
                data-id="evergreen-status-toggle"
              />
            </div>
          </MenuItem>
          <MenuItem
            data-id="internal-notes"
            onClick={() => {
              setNotesOpen(!isNotesOpen);
              closeMenu(null);
            }}
          >
            <StickyNote2Rounded htmlColor="info.dark" fontSize="medium" />
            Internal Notes
          </MenuItem>

          {props.canOperateWithVideoVersionUpload && (
            <MenuItem
              data-id="edit-video"
              onClick={() => {
                dispatch(
                  openVideoVersionUploadAction({
                    videoId: props.videoId,
                    access: props.videoAccess,
                  }),
                );
                closeMenu(null);
              }}
              disabled={shouldDisableUploadVersion}
            >
              <CloudUploadOutlined htmlColor="info.dark" fontSize="medium" />
              Upload New Video Version
            </MenuItem>
          )}

          {(props.canArchive || hasPermission(VIDEO_ADMIN, userPermissions)) && <Divider />}
          {props.canArchive && (
            <MenuItem
              data-id="archive-video"
              onClick={() => {
                props.onArchiveClick();
                closeMenu();
              }}
            >
              <Inventory htmlColor="info.dark" fontSize="medium" />
              Archive
            </MenuItem>
          )}
          {hasPermission(VIDEO_ADMIN, userPermissions) && (
            <MenuItem
              data-id="delete-video"
              onClick={() => {
                setIsOpenPermanentDelete(true);
                closeMenu();
              }}
            >
              <DeleteForever htmlColor="error.main" fontSize="medium" />
              Permanently Delete Video
            </MenuItem>
          )}
        </Menu>
      )}
      {isOpenPermanentDelete && (
        <Dialog fullWidth maxWidth="xs" open={isOpenPermanentDelete} onClose={() => setIsOpenPermanentDelete(false)}>
          <DialogTitle onClose={() => setIsOpenPermanentDelete(false)}>Delete Video Confirmation</DialogTitle>
          <DialogContent>
            The video will be permanently deleted with all related data from the video library and all playlists and
            channels. Are you sure you would like to proceed?
          </DialogContent>
          <DialogActions>
            <Button size="small" variant="outlined" onClick={() => setIsOpenPermanentDelete(false)} color="primary">
              Cancel
            </Button>
            <Button
              size="small"
              variant="contained"
              onClick={() => {
                props.onDeleteClick();
                setIsOpenPermanentDelete(false);
              }}
              color="error"
            >
              Delete
            </Button>
          </DialogActions>
        </Dialog>
      )}

      {isNotesOpen && (
        <Dialog
          fullWidth
          maxWidth="xs"
          open={isNotesOpen}
          onClose={() => {
            setNotesOpen(false);
            setNotes$(notes);
          }}
        >
          <DialogTitle
            onClose={() => {
              setNotesOpen(false);
              setNotes$(notes);
            }}
          >
            Internal Notes
          </DialogTitle>
          <DialogContent>
            <DialogContentText>
              <Stack spacing={2}>
                <TextField
                  value={notes$}
                  label="Enter Internal Notes"
                  onChange={(e) => {
                    if (e.target.value?.length <= 1024) {
                      setNotes$(e.target.value);
                    }
                  }}
                  variant="outlined"
                  size="small"
                  multiline
                  rows={5}
                  fullWidth
                />
                <Typography variant="caption" component="div" className={styles.NotesLength}>
                  {`${notes$?.length ?? 0}/1024`}
                </Typography>
              </Stack>
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button
              size="small"
              variant="contained"
              onClick={() => {
                props.handleNotesChange(notes$);
                setNotesOpen(false);
              }}
              color="primary"
            >
              Save
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

MenuComponent.propTypes = {
  onArchiveClick: PropTypes.func.isRequired,
  onDeleteClick: PropTypes.func.isRequired,
  evergreen: PropTypes.bool,
  onEvergreenSet: PropTypes.func.isRequired,
  contentOwner: PropTypes.number.isRequired,
  notes: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  shouldOpenVideoMenuImmediately: PropTypes.bool,
  handleNotesChange: PropTypes.func.isRequired,
  onPublish: PropTypes.func.isRequired,
  videoTitle: PropTypes.string.isRequired,
  videoId: PropTypes.string.isRequired,
  canArchive: PropTypes.bool.isRequired,
  canEditVideo: PropTypes.bool.isRequired,
  videoAccess: PropTypes.shape({ level: PropTypes.string }).isRequired,
  canOperateWithVideoVersionUpload: PropTypes.bool.isRequired,
  onDownloadTags: PropTypes.func.isRequired,
};

export default MenuComponent;
