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 Avatar from '@mui/material/Avatar';
import ListItemIcon from '@mui/material/ListItemIcon';
import LibraryMusicIcon from '@mui/icons-material/LibraryMusic';
import FolderIcon from '@mui/icons-material/Folder';
import ImageIcon from '@mui/icons-material/Image';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { makeStyles } from '@material-ui/core'
import { useSelector } from 'react-redux';
import { useState,useEffect} from 'react';

import { TMessages,TMessage } from '../../../../../typescript/redux/messages/types';
import { getMessagesMemo } from '../../../../../redux/messages/selector';
import { firstLetter,slicedWord,handleSort,prodAwsS3,copied,handleDownload } from '../../../../../helpers';
import { pinMessageById } from '../../../../../api-data';

const useStyles = makeStyles({
  container: {
    marginLeft: 20,
    display: 'flex',
    alignContent: 'center',
    alignItems:'center'
  },
  iconClose: {
    '&:hover': {
      transform: 'rotate(180deg)',
      transition: 'all 250ms ease-out ',
    }
  },
  listWrapper: {
    background: '#fdfdfd',
    padding:0
  },
  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',
    cursor: 'pointer',
    '&:hover': {
      color: '#016cc3'
    },
  },
})

const PinnedBar = ({divRef}:{divRef: any | null}) => {
  const classes = useStyles()
  const messagesMemo = useSelector(getMessagesMemo)
  const [pinnedArr, setPinnedArr] = useState<TMessages>([])
  const [openedPin, setOpenedPin] = useState<TMessage | null>(null)
  const [openedIndex, setOpenedIndex] = useState<number>(0)
  const [modal, setModal] = useState<boolean>(false)
  
  const handleActivePin = () => {
    const childNodes = divRef.current.childNodes[0].childNodes
    let toScrollNode:any
    if (pinnedArr.length - 1 === openedIndex) {
      setOpenedIndex(0)
      toScrollNode = [ ...childNodes ].find((el:any) => el.id === pinnedArr[0]._id)
    } else {
      setOpenedIndex(prevState => prevState + 1)
      toScrollNode = [...childNodes].find((el: any) => el.id === pinnedArr[openedIndex + 1]._id)
    }
    toScrollNode.style.boxShadow = '0px 0px 6px 0px #555555'
    toScrollNode.scrollIntoView()
    setTimeout(() => {
      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(() => {
    const messages = messagesMemo.filter((el) => el.pinned === true)
    setPinnedArr(handleSort('updatedAt', messages, false))
  }, [messagesMemo])

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

  return openedPin ?
    <Stack className={classes.container} direction="row">
      <ul className={classes.listWrapper}>
        <MenuItem onClick={handleActivePin}>
          <ListItemIcon >
            <Avatar alt={openedPin.name} src={openedPin.avatarUrl?`${prodAwsS3}/${openedPin.avatarUrl}`:undefined}
              sx={{ background: openedPin.color, width: 44, height: 44 }}>
              {!openedPin.avatarUrl&&`${firstLetter(openedPin.name)}${firstLetter(openedPin.lastName)}`}
          </Avatar>
          </ListItemIcon>           
          <ListItemText style={{marginLeft:20}}
            primary={`${firstLetter(openedPin.name)}${slicedWord(openedPin.name, 15, 1)}
            ${firstLetter(openedPin.lastName)}${slicedWord(openedPin.lastName, 15, 1)}`}
            primaryTypographyProps={{fontSize:16 }}
            secondary={slicedWord(openedPin.message, 20, 1)}
            secondaryTypographyProps={{fontSize: 12 }} />
          <ListItemText style={{marginLeft:20}}
            primary={`Pinned Message ${openedIndex + 1} of ${pinnedArr.length}`}
            primaryTypographyProps={{ color: "#0379af",fontSize:16 }}
            secondary={`Type : ${openedPin.type.toUpperCase()}`}
            secondaryTypographyProps={{ fontSize:16 }}/>          
        </MenuItem>
      </ul>
      <ListItemAvatar style={{marginLeft:10}}>
        {openedPin.type === 'text' &&<CopyToClipboard onCopy={() => copied('Message')} text={openedPin.message}>
           <ContentCopyIcon className={classes.folderIcon} fontSize='large' />
        </CopyToClipboard>}
        {openedPin.type === 'audio' &&<LibraryMusicIcon onClick={() =>
          handleDownload(`${prodAwsS3}/${openedPin.message}`, openedPin.fullType)}
          className={classes.folderIcon} fontSize='large' />}
        {openedPin.type === 'video' &&<VideoLibraryIcon onClick={() =>
          handleDownload(`${prodAwsS3}/${openedPin.message}`, openedPin.fullType)}
          className={classes.folderIcon} fontSize='large' />}
        {openedPin.type === 'image' &&<ImageIcon onClick={() =>
          handleDownload(`${prodAwsS3}/${openedPin.message}`, openedPin.fullType)}
          className={classes.folderIcon} fontSize='large' />}
        {openedPin.type === 'pdf' ?<FolderIcon onClick={() =>
          handleDownload(`${prodAwsS3}/${openedPin.message}`, openedPin.fullType)}
          className={classes.folderIcon} fontSize='large' />:null}         
        {openedPin.type === 'docx' ?<FolderIcon onClick={() =>
          handleDownload(`${prodAwsS3}/${openedPin.message}`, openedPin.fullType)}
          className={classes.folderIcon} fontSize='large' />:null}        
      </ListItemAvatar>
      <IconButton onClick={() => setModal(true)} aria-label="delete" size="medium">
        <CloseIcon className={classes.iconClose} fontSize='medium'/>
      </IconButton>
      <IconButton 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