import { makeStyles } from '@material-ui/core'
import { useSelector } from 'react-redux'
import React, { useState } 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 Search from './Search'
import AlertInfo from "../../../reusableComponents/AlertInfo";
import { getMessages } from '../../../../redux/messages/selector'
import { getChat } from '../../../../redux/chat/selector'
import { timeStampEU, timeStampFilter, firstLetter, slicedWord, handleSort,prodAwsS3 } from '../../../../helpers'
import { TMessages } 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',
    }
  },
})

const SearchList= ({chatDivRef}:{chatDivRef: any | null}) => {
    const classes = useStyles()
    const { sort } = useSelector(getChat)
    const messages = useSelector(getMessages)
    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.boxShadow = '0px 0px 6px 0px #555555'
        toScrollNode.scrollIntoView({ behavior: 'smooth' })
        setTimeout(() => {
          toScrollNode.style.boxShadow = 'unset'
        }, 2000)
      }
    }

    const filteredMessages = (arr:TMessages) => arr.filter((el) => {
      if (!date) {
        return el.message.toLowerCase().includes(value.toLowerCase())
      } else if (el.message.toLowerCase().includes(value.toLowerCase())
        && timeStampFilter(date) === timeStampFilter(el.createdAt)) {
        return el
      }
    })
  
  const arr: TMessages = filteredMessages(handleSort('createdAt', messages, sort))
  
return (
   <div className={classes.container}>
    <Search handleSearch={handleSearch} value={value}
      setDate={setDate} date={date} />
     <div className={messages.length > 0 ?classes.list:undefined}>
      {messages.length > 0 ? arr.length > 0 ?
        <List sx={{ width: '100%' }}>
          {arr.map(({ name, lastName, avatarUrl, color, message, createdAt,_id }) =>
          <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: 44, height: 44, 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"
                           >
                             {message}
                           </Typography>
                           {timeStampEU(createdAt)}
                         </>}
                     />
                </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