import { useState,useEffect,useMemo } from 'react';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core'
import { styled } from '@mui/material/styles';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Box from '@mui/material/Box';

import AudioList from './AudioList';
import MediaList from './MediaList';
import FilesList from './FilesList';
import TextList from './TextList';
import VideoList from './VideoList'
import { getOpenPinned } from '../../../../../redux/control/selector';
import { getPinnedMessagesMemo } from '../../../../../redux/pinnedMessages/selector'; 
import { getMessagesMemo } from '../../../../../redux/messages/selector'
import { handleSort,filterBy } from '../../../../../helpers';
import { getChat } from '../../../../../redux/chat/selector'
import { TMessages,TMessage } from '../../../../../typescript/redux/messages/types'

const useStyles = makeStyles({
container: {
  height: '7vh',
    display: "flex",
    alignContent: "end",
    alignItems: "end",
    width:'100%',
    borderBottom: 'solid 2px #dddddd',
 },
})

interface StyledTabsProps {
  children?: React.ReactNode;
  value: number;
  onChange: (event: React.SyntheticEvent, newValue: number) => void;
}

const StyledTabs = styled((props: StyledTabsProps) => (
  <Tabs
    {...props}
    TabIndicatorProps={{ children: <span className="MuiTabs-indicatorSpan" /> }}
  />
))({
  '& .MuiTabs-flexContainer': {
    display: "flex",
    width: '100%',
    padding:'0px 10px',
    justifyContent: "space-between"
  },
  '& .MuiTabs-indicator': {
    height: 0,
    backgroundColor: 'transparent',
    borderBottom: '3px solid #1976d2',
    borderLeft: '3px solid transparent',
    borderRight: '3px solid transparent',
  },
});

const StyledTab = styled((props:{label: string}) => <Tab disableRipple {...props} />)(
  () => ({
    fontSize: '1rem',
    fontWeight: 550,
    textTransform: 'none',
    minWidth:'auto'
  }),
);

interface IProfileLists {
  setDisabled: React.Dispatch<boolean>,
  chatDivRef: any | null,
}

const ProfileLists = ({setDisabled,chatDivRef}:IProfileLists) => {
    const classes = useStyles()
    const { sort } = useSelector(getChat)
    const openPinned = useSelector(getOpenPinned)
    const messagesMemo = useSelector(getMessagesMemo)
    const pinnedMessagesMemo = useSelector(getPinnedMessagesMemo)
    const [isActive, setIsActive] = useState<number>(0)
  
    const handleIsActive = (_e:any,newValue: number): void => setIsActive(newValue)
    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) => filterBy[isActive].includes(el.type)),[isActive,messagesMemo,openPinned,pinnedMessagesMemo,sort])

    useEffect(() => {
      setDisabled(filteredAndSorted.length > 0?false:true)
    }, [filteredAndSorted, setDisabled])
  
    return (
      <>
        <Box className={classes.container}>
          <StyledTabs sx={{width:'100%'}} onChange={handleIsActive} value={isActive} aria-label="wrapped label tabs example">
            <StyledTab label='Files'/>
            <StyledTab label='Media'/>
            <StyledTab label='Text'/>
            <StyledTab label='Audio'/>
            <StyledTab label='Video'/>
          </StyledTabs>
        </Box>
        {isActive === 0 && <FilesList filteredAndSorted={filteredAndSorted} handleScrollToTheMessage={handleScrollToTheMessage} openPinned={openPinned}/>}            
        {isActive === 1 && <MediaList filteredAndSorted={filteredAndSorted} handleScrollToTheMessage={handleScrollToTheMessage} openPinned={openPinned}/>}
        {isActive === 2 && <TextList filteredAndSorted={filteredAndSorted} handleScrollToTheMessage={handleScrollToTheMessage} openPinned={openPinned}/>}
        {isActive === 3 && <AudioList filteredAndSorted={filteredAndSorted} handleScrollToTheMessage={handleScrollToTheMessage} openPinned={openPinned}/>}
        {isActive === 4 && <VideoList filteredAndSorted={filteredAndSorted} handleScrollToTheMessage={handleScrollToTheMessage} openPinned={openPinned}/>}
    </>      
    )
}

export default ProfileLists