import Stack from '@mui/material/Stack';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import ListItemText from '@mui/material/ListItemText';
import CloseIcon from '@mui/icons-material/Close';
import MenuOpenIcon from '@mui/icons-material/MenuOpen';
import Button from '@mui/material/Button';
import LibraryMusicIcon from '@mui/icons-material/LibraryMusic';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import ImageIcon from '@mui/icons-material/Image';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';
import { makeStyles } from '@material-ui/core'
import { useSelector } from 'react-redux';
import { useState,useEffect} from 'react';

import { TMessage } from '../../../../../typescript/redux/messages/types';
import { getPinnedMessagesMemo } from '../../../../../redux/pinnedMessages/selector';
import { pinMessageById } from '../../../../../api-data';

const useStyles = makeStyles({
  container: {
    marginLeft: 20,
    display: 'flex',
    alignContent: 'center',
    alignItems: 'center',
    position:'relative'
  },
  iconClose: {
    '&:hover': {
      transform: 'rotate(180deg)',
      transition: 'all 250ms ease-out ',
    }
  },
  listWrapper: {
    background: '#fdfdfd',
    padding: 0,
  },
  listWrapperDashes: {
    position: 'absolute',
    top: 0,
    width: 2,
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent:'space-around',
    flexWrap:'nowrap',
    listStyle:'none'
  },  
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
    zIndex: 100,
    backgroundColor: 'rgba(104, 105, 104, 0.6)',
    overflowY: 'hidden',
  },
  modalUnpin: {
    background: '#ffffff',
    position: 'absolute',
    content:'',
    width: '20%',
    height:'auto',
    left: '40%',
    bottom: '48.5%',
    borderRadius: 10,
    padding: 10,
    display: 'flex',
    flexDirection:'column'
  },
  folderIcon: {
    color: '#54b0fc',
  },
})

interface IPinnedBar {
  chatDivRef: any | null,
  handleOpenPinned: () => void,
}

const PinnedBar = ({chatDivRef,handleOpenPinned}:IPinnedBar) => {
  const classes = useStyles()
  const pinnedMessagesMemo = useSelector(getPinnedMessagesMemo)
  const [openedPin, setOpenedPin] = useState<TMessage | null>(null)
  const [openedIndex, setOpenedIndex] = useState<number>(0)
  const [modal, setModal] = useState<boolean>(false)
  const heightPerDash = 100/pinnedMessagesMemo.length
  const heightOfDash = heightPerDash-((heightPerDash/100)*20)
  
  const handleActivePin = () => {
    const childNodes = chatDivRef.current.childNodes[0].childNodes
    let toScrollNode: any
    if (pinnedMessagesMemo.length - 1 === openedIndex) {
      setOpenedIndex(0)
      toScrollNode = [ ...childNodes ].find((el:any) => el.id === pinnedMessagesMemo[0]._id)
    } else {
      setOpenedIndex(prevState => prevState + 1)
      toScrollNode = [...childNodes].find((el: any) => el.id === pinnedMessagesMemo[openedIndex + 1]._id)
    }
    if (toScrollNode) {
      toScrollNode = [...toScrollNode.childNodes].slice(-1)[0]
      toScrollNode.style.backgroundColor = 'rgba(70, 70, 70, 0.4)'
      toScrollNode.style.boxShadow = '0px 0px 6px 0px #ffffff'
      toScrollNode.scrollIntoView({ behavior: 'smooth' })
      setTimeout(() => {
        toScrollNode.style.backgroundColor = 'unset'
        toScrollNode.style.boxShadow = 'unset'
      }, 2000)
    }
  }
  const handleUnpin = (e: any) => {
    const id = e.target.id
    if (id === 'overlay' || id === 'cancel') return setModal(false)
    if (id === 'unpin' && openedPin) {
      pinMessageById(openedPin._id, !openedPin.pinned)
      setModal(false)
      if (openedIndex - 1 >= 0) {
        return setOpenedIndex(prevState => prevState - 1)
      } else {
        setOpenedIndex(0)
      }
    }
  }

  useEffect(() => {
    setOpenedPin(pinnedMessagesMemo[openedIndex])
  }, [pinnedMessagesMemo,openedIndex])

  return openedPin ?
    <Stack className={classes.container} direction="row">
      <ul className={classes.listWrapperDashes}>
        {pinnedMessagesMemo.map(({ _id }) =>
          <li key={_id} style={{backgroundColor:openedPin._id === _id? "#00aeff":"#addbf0",
            height: `${heightOfDash}%`}}></li>)}
      </ul>      
      <ul className={classes.listWrapper}>
        <MenuItem onClick={handleActivePin}>
          <ListItemText style={{margin:'0px 10px 0px 20px'}}
            primary={`Pinned Message ${openedIndex + 1} of ${pinnedMessagesMemo.length}`}
            primaryTypographyProps={{ color: "#0379af",fontSize:16 }}
            secondary={`Type : ${openedPin.type.toUpperCase()}`}
            secondaryTypographyProps={{ fontSize:16 }}/> 
          {openedPin.type === 'text' &&<ContentCopyIcon className={classes.folderIcon} fontSize='large' />}
          {openedPin.type === 'audio' &&<LibraryMusicIcon className={classes.folderIcon} fontSize='large' />}
          {openedPin.type === 'video' &&<VideoLibraryIcon className={classes.folderIcon} fontSize='large' />}
          {openedPin.type === 'image' &&<ImageIcon className={classes.folderIcon} fontSize='large' />}
          {openedPin.type === 'pdf'&&<InsertDriveFileIcon className={classes.folderIcon} fontSize='large' />}         
          {openedPin.type === 'docx'&&<InsertDriveFileIcon className={classes.folderIcon} fontSize='large' />}           
        </MenuItem>      
      </ul>
      <IconButton onClick={() => setModal(true)} aria-label="delete" size="medium">
        <CloseIcon className={classes.iconClose} fontSize='medium'/>
      </IconButton>
      <IconButton onClick={handleOpenPinned} aria-label="delete" size="medium">
        <MenuOpenIcon fontSize='medium'/>
      </IconButton>
      {modal &&
      <div onClick={handleUnpin} className={classes.overlay} id='overlay'>
        <div className={classes.modalUnpin}>
          <h3 style={{color: '#2c2c2c'}}>Telegram</h3>
          <p style={{ color: '#050505' }}>Would you like to unpin this message?</p>
          <Button id='unpin' variant="text" color="error" style={{fontWeight:500,fontSize:22}}>
            UNPIN
          </Button>         
          <Button id='cancel' variant="text" style={{fontWeight:500,fontSize:22}}>
             CANCEL
          </Button>
        </div>  
      </div>}        
    </Stack> :
    null
}

export default PinnedBar