import Grid from '@mui/material/Grid'
import { useState,useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'

import HeaderBar from './HeaderBar'
import ChatBar from './ChatBar'
import { getPinnedMessagesMemo } from '../../../redux/pinnedMessages/selector'
import { TRightIsOpen } from '../../../typescript/redux/control/types'
import { getOpenPinned } from '../../../redux/control/selector'
import { actionOpenPinned } from '../../../redux/control/action'
import { unpinAllMessagesById } from '../../../api-data'

interface ICentralBar {
  rightIsOpen: TRightIsOpen,
  chatDivRef: any | null,
  companionId: string,
  backgroundImage: string,
  handleStartCall: () => void,
}

const CentralBar = ({rightIsOpen,chatDivRef,companionId,backgroundImage,handleStartCall}:ICentralBar) => {
  const dispatch = useDispatch()
  const pinnedMessagesMemo = useSelector(getPinnedMessagesMemo)
  const openPinned = useSelector(getOpenPinned)
  const [selectedArr, setSelectedArr] = useState<string[] | []>([])
  const [isSomeSelected, setIsSomeSelected] = useState<boolean>(false)
  
  const handleClearSelect = () => {
    selectedArr.length > 0 && setSelectedArr([])
    isSomeSelected && setIsSomeSelected(false)
  }

  const handleUnpinAll = () => {
    openPinned && dispatch(actionOpenPinned(false))
    unpinAllMessagesById(pinnedMessagesMemo.map(({_id}) => _id))
  }
  
  useEffect(() => {
    if(pinnedMessagesMemo.length === 0 && openPinned) dispatch(actionOpenPinned(false))
  }, [openPinned,pinnedMessagesMemo,dispatch])
  
  useEffect(() => {
    setIsSomeSelected(false)
    setSelectedArr([])
  }, [companionId])  

    return ( 
     <Grid item lg={rightIsOpen?8:12}>
        <Grid item lg={12} >
          <HeaderBar chatDivRef={chatDivRef} selectedArr={selectedArr} isSomeSelected={isSomeSelected}
            handleClearSelect={handleClearSelect} setIsSomeSelected={setIsSomeSelected}
            openPinned={openPinned} pinnedMessagesMemo={pinnedMessagesMemo} handleStartCall={handleStartCall}/>
        </Grid>          
        <Grid item lg={12} style={{backgroundImage}}>
          <ChatBar chatDivRef={chatDivRef} selectedArr={selectedArr} setSelectedArr={setSelectedArr}
            isSomeSelected={isSomeSelected} setIsSomeSelected={setIsSomeSelected}
            openPinned={openPinned} pinnedMessagesMemo={pinnedMessagesMemo} handleUnpinAll={handleUnpinAll}/>
        </Grid>
      </Grid>
    )   
}

export default CentralBar