import { makeStyles } from '@material-ui/core'
import { useSelector } from 'react-redux'
import { useState,useMemo } from 'react'
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
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 Search from './Search'
import AlertInfo from "../../../reusableComponents/AlertInfo";
import { getMessagesMemo } from '../../../../redux/messages/selector'
import { getOpenPinned } from '../../../../redux/control/selector';
import { getPinnedMessagesMemo } from '../../../../redux/pinnedMessages/selector'
import { getChat } from '../../../../redux/chat/selector'
import { timeStampEU, timeStampFilter, firstLetter, slicedWord, handleSort,prodAwsS3 } from '../../../../helpers'
import { TMessages,TMessage } from '../../../../typescript/redux/messages/types';

const useStyles = makeStyles({
  container: {
    height: '100%',
    backgroundColor: '#ffffff'
  },
  list: {
    maxHeight: '93vh',
    overflowY: 'scroll',
    '&::-webkit-scrollbar': {
      width: '0.4em'
    },
    '&::-webkit-scrollbar-track': {
      boxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
      webkitBoxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
      backgroundColor: '#eceeec',
    },
    '&::-webkit-scrollbar-thumb': {
      backgroundColor: '#ccc8c8',
    },
    "&::-webkit-scrollbar-thumb:focus": {
      backgroundColor: "#959595",
    },
    "&::-webkit-scrollbar-thumb:active": {
      backgroundColor: "#959595",
    },    
  },
  listItem: {
    cursor:'pointer',
    '&:hover': {
      backgroundColor: '#f0f0f0',
    }
  },
  folderIcon: {
    margin: 'auto 0px',
    color: '#54b0fc',
  }
})

interface ISearchList {
  chatDivRef: any | null,
}

const SearchList= ({chatDivRef}:ISearchList) => {
    const classes = useStyles()
    const { sort } = useSelector(getChat)
    const openPinned = useSelector(getOpenPinned)
    const messagesMemo = useSelector(getMessagesMemo)
    const pinnedMessagesMemo = useSelector(getPinnedMessagesMemo)
    const [value, setValue] = useState<string>('')
    const [date, setDate] = useState<any>('');
    const handleSearch = (e: React.ChangeEvent<HTMLInputElement>): void => setValue(e.target.value)
    const handleScrollToTheMessage = (_id: string) => {
      const childNodes = chatDivRef.current.childNodes[0].childNodes
      let toScrollNode = [...childNodes].find((el: any) => el.id === _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 filteredAndSorted: TMessages = useMemo(() => handleSort('createdAt', !openPinned ? messagesMemo : pinnedMessagesMemo, sort)
    .filter((el: TMessage) => {
      if (!date) {
        return el.message.toLowerCase().includes(value.toLowerCase())
      } else if (el.message.toLowerCase().includes(value.toLowerCase())
        && timeStampFilter(date) === timeStampFilter(el.createdAt)) {
        return el
      } return undefined
    }),[messagesMemo,date,sort,value,openPinned,pinnedMessagesMemo]) 
  
return (
   <div className={classes.container}>
    <Search handleSearch={handleSearch} value={value}
      setDate={setDate} date={date} />
     <div className={messagesMemo.length > 0 ?classes.list:undefined}>
      {messagesMemo.length > 0 ? filteredAndSorted.length > 0 ?
        <List sx={{ width: '100%' }}>
          {filteredAndSorted.map(({ name, lastName, avatarUrl, color, message, createdAt,_id,fullType,type }) =>
          <div key={createdAt}>
              <ListItem onClick={() => handleScrollToTheMessage(_id)}
                alignItems="flex-start" className={classes.listItem}>
                     <ListItemAvatar>
                        <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
                          sx={{ background: color, width: 40, height: 40, marginRight:2 }}>
                          {!avatarUrl&&`${firstLetter(name)}${firstLetter(lastName)}`}
                        </Avatar>
                     </ListItemAvatar>
                     <ListItemText
                       primary={`${firstLetter(name)}${slicedWord(name, 15, 1)} 
                        ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
                       secondary={<>
                           <Typography
                             sx={{ display: 'block',wordBreak:'break-word' }}
                             component="span"
                             variant="body2"
                             color="text.primary"
                           >
                             {type === 'text'? message : fullType}
                           </Typography>
                           {timeStampEU(createdAt)}
                         </>}
                     />
                     {type === 'text' &&<ContentCopyIcon className={classes.folderIcon} fontSize='large'/>}
                     {type !== 'text'&&fullType.includes('audio') &&<LibraryMusicIcon className={classes.folderIcon} fontSize='large' />}
                     {type !== 'text'&&fullType.includes('video') &&<VideoLibraryIcon className={classes.folderIcon} fontSize='large' />}
                     {type !== 'text'&&fullType.includes('image') &&<ImageIcon className={classes.folderIcon} fontSize='large' />}
                     {type !== 'text' && fullType.includes('application') && <InsertDriveFileIcon className={classes.folderIcon} fontSize='large' />}
                </ListItem>
              <Divider variant="inset"/>
            </div>)}
          </List> :
        <AlertInfo name={`Can not find message by request: ${value}`}/>:
        <AlertInfo name='You do not have messages yet!' />}
     </div>
   </div>
  )
}

export default SearchList