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 { makeStyles } from '@material-ui/core'
import { useDispatch,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 } from '../../../../../helpers';

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',
    width: 400,
    padding:0
  },  
})

const PinnedBar = () => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const messagesMemo = useSelector(getMessagesMemo)
  const [pinnedArr, setPinnedArr] = useState<TMessages>([])
  const [openedPin, setOpenedPin] = useState<TMessage | null>(null)
  const [openIndex, setOpenIndex] = useState<number>(0)
  const handleActivePin = () => setOpenIndex(openIndex => openIndex + 1)
  
  useEffect(() => {
    const messages = messagesMemo.filter((el) => el.pinned === true)
    setPinnedArr(handleSort('updatedAt', messages, true))
  }, [messagesMemo])

  useEffect(() => {
    const pinnedObj = pinnedArr[openIndex]
    if (pinnedObj) setOpenedPin(pinnedObj)
    else setOpenIndex(0)
  }, [openIndex,pinnedArr])   

  return openedPin ?
    <Stack className={classes.container} direction="row">
      <ul className={classes.listWrapper}>
        <MenuItem onClick={handleActivePin}>
          <ListItemText primary={`${firstLetter(openedPin.name)}${slicedWord(openedPin.name, 15, 1)} 
            ${firstLetter(openedPin.lastName)}${slicedWord(openedPin.lastName, 15, 1)}`}
            primaryTypographyProps={{fontSize:16 }}
            secondary={slicedWord(openedPin.message, 40, 1)}
            secondaryTypographyProps={{fontSize: 12 }} />
          <ListItemText primary={`Pinned Message #${openIndex+1}`}
            primaryTypographyProps={{ color: "#0379af",fontSize:16 }}
            secondary={`Type : ${openedPin.type}`}
            secondaryTypographyProps={{ fontSize:16 }}/>          
        </MenuItem>
      </ul>      
      <IconButton  aria-label="delete" size="medium">
        <CloseIcon className={classes.iconClose} fontSize='medium'/>
      </IconButton>          
    </Stack> :
    null
}

export default PinnedBar