import { useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import { useTheme } from '@mui/material/styles';
import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import ClickAwayListener from '@mui/material/ClickAwayListener';

import { paths } from '@/routes/paths';
import { useBoolean, useRouter } from '@/hooks';
import { alpha } from '@mui/material/styles';
import { useResponsive } from '@/hooks/use-responsive';

import Iconify from '@/shared/components/iconify';
import Scrollbar from '@/shared/components/scrollbar';

import { IChatParticipant, IChatConversations, IClient} from '@/shared/types/chat';

import { useCollapseNav } from '@/hooks';
import ChatNavItem from './chat-nav-item';
import ChatNavAccount from './chat-nav-account';
import { ChatNavItemSkeleton } from './chat-skeleton';
import ChatNavSearchResults from './chat-nav-search-results';
import { BottomNavigation, BottomNavigationAction, Popover, Tooltip, Typography } from '@mui/material';
import { bgBlur } from '@/shared/theme/css';
import React from 'react';
import ChatContacts from './chat-contacts';
import ChatNewMessage from './chat-new-message';
import ChatNewChannel from './chat-new-channel';
import ChatSettings from './chat-settings';
import ChatNotifications from './chat-notifications';
import ChatManageAnonymity from './chat-manage-anonymity';

// ----------------------------------------------------------------------



const NAV_COLLAPSE_WIDTH = 96;

type Props = {
  loading: boolean;
  selectedConversationId: string;
  contacts: IClient[];
  conversations: IChatConversations;
};

export default function ChatNav({
  loading,
  contacts,
  conversations,
  selectedConversationId,
}: Props) {
  const theme = useTheme();

  const router = useRouter();

  const mdUp = useResponsive('up', 'md');

  const [showActions, setShowActions] = useState(false);

  const [searchClicked,setSearchClicked]= useState(false);

  const [showContactsClicked,setShowContactsClicked]= useState(false);

  const [newDiscussionClicked,setNewDiscussionClicked]= useState(false);

  const [showSettingsClicked,setShowSettingsClicked]= useState(false);

  const notifs = useBoolean();

  const anonymity = useBoolean();

  const newChannel = useBoolean();

  const [value, setValue] = useState('direct');

  

  const handleChange = (event: React.SyntheticEvent, newValue: string) => {
    setValue(newValue);
  };
   
  const NAV_WIDTH = mdUp ? 320:'100%'; ///////CHANGES

  //--------------- for test------------------------

  const typeConversation = (value==='direct')?'PEER_TO_PEER': 'CHANNEL';
  const convarsationData = conversations.allIds.filter((convId)=>conversations.byId[convId].typeConv===typeConversation);
  

  const {
    collapseDesktop,
    onCloseDesktop,
    onCollapseDesktop,
    //
    openMobile,
    onOpenMobile,
    onCloseMobile,
  } = useCollapseNav();


  const [searchContacts, setSearchContacts] = useState<{
    query: string;
    results: IClient[];
  }>({
    query: '',
    results: [],
  });

  useEffect(() => {
    if (!mdUp) {
      onCloseDesktop();
      // onCollapseDesktop();
    }
  }, [onCloseDesktop, mdUp]);

  const handleToggleNav = useCallback(() => {
    // if (mdUp) {
      onCollapseDesktop();
      handleCloseContacts();
      console.log('up');
    // } 
    // else {
    //   onCloseMobile();
    // }
  }, [mdUp,onCloseMobile,onCollapseDesktop]);

  const handleClickCompose = useCallback(() => {
    if (!mdUp) {
      onCloseMobile();
    }
    router.push(paths.dashboard.chat);
  }, [mdUp, onCloseMobile, router]);

  const handleSearchContacts = useCallback(
    (inputValue: string) => {
      setSearchContacts((prevState) => ({
        ...prevState,
        query: inputValue,
      }));

      if (inputValue) {
        const results = contacts.filter((contact) =>
          contact.firstname.toLowerCase().includes(inputValue)
        );

        setSearchContacts((prevState) => ({
          ...prevState,
          results,
        }));
      }
    },
    [contacts]
  );

  const handleClickAwaySearch = useCallback(() => {
    setSearchContacts({
      query: '',
      results: [],
    });
  }, []);

  const handleClickResult = useCallback(
    (result: IClient) => {
      handleClickAwaySearch();

      router.push(`${paths.dashboard.chat}?id=${result.id}`);
    },
    [handleClickAwaySearch, router]
  );
  
   // Popover management for conversation actions

   const handleActionsClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
    setShowActions(!showActions);
    setSearchClicked(false);
    setShowContactsClicked(false);
    setNewDiscussionClicked(false);
    console.log('clicked')
  };

  const handleCloseActions = () => {
    setAnchorEl(null);
    setShowActions(false);
    
  };
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  ///

    /// Settings Action ///////////////////////

    const handleSettings = ()=>{
      handleCloseActions();
      setShowSettingsClicked(!showSettingsClicked);
      
    }
    const handleCloseSettings = () => {
      setShowSettingsClicked(false);
    };
    //////////////////////////////////////////////

  /// Serach Action ///////////////////////

  const handleSearch = ()=>{
    setSearchClicked(!searchClicked);
    setShowContactsClicked(false);
    setShowActions(false);
    setSearchClicked(false);
    setNewDiscussionClicked(false);
  }
  const handleCloseSearch = () => {
    setSearchClicked(false);
  };
  //////////////////////////////////////////////

  //// Contacts //////////////////////////////////
  const handleContactsAction = ()=>{
    setShowContactsClicked(!showContactsClicked);
    setShowActions(false);
    setSearchClicked(false);
    setNewDiscussionClicked(false);
  }
  const handleCloseContacts = () => {
    setShowContactsClicked(false);
  };

  ////////////////////////////////////

  //// New Discussion ///////////////////////

  const handleNewDiscussionAction = ()=>{
    if(mdUp){
      handleClickCompose();
    }else{
      setNewDiscussionClicked(!newDiscussionClicked);
    } 
    setShowContactsClicked(false);
    handleCloseActions();
    setSearchClicked(false);
  }
  const handleCloseNewDiscussion = () => {
    setNewDiscussionClicked(false);
  };

  ///////////////////////////////////////////

  //// New Channel ///////////////////////

  const handleNewChannelAction = ()=>{
    handleCloseActions();
    newChannel.onTrue()
  }

  ///////////////////////////////////////////

   //// Notifications ///////////////////////

   const handleNotifsAction = ()=>{
    handleCloseActions();
    notifs.onTrue();
  }

  ///////////////////////////////////////////

  //// Anonymity ///////////////////////

    const handleAnonymityAction = ()=>{
    handleCloseActions();
    anonymity.onTrue();
  }

  ///////////////////////////////////////////

  const renderSkeleton = (
    <>
      {[...Array(12)].map((_, index) => (
        <ChatNavItemSkeleton key={index} />
      ))}
    </>
  );

  const renderList = (
    <>

       {convarsationData.map((conversationId) =>
        (
        <ChatNavItem
          key={conversationId}
          collapse={collapseDesktop}
          conversation={conversations.byId[conversationId]}
          selected={conversationId === selectedConversationId}
          onCloseMobile={onCloseMobile}
        />
      ))}
    </>
  );

  const renderListResults = (
    <ChatNavSearchResults
      query={searchContacts.query}
      results={searchContacts.results}
      onClickResult={handleClickResult}
    />
  );

  const renderActions = (
    <Popover
      id={id}
      open={open}
      anchorEl={anchorEl}
      onClose={handleCloseActions}
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'right',
      }}
      transformOrigin={{
        vertical: 'top',
        horizontal: 'right',
      }}
      PaperProps={{
        sx:{border:(theme) => `solid 2px ${theme.palette.divider}`,
          marginTop:0,
           width:mdUp?250:250},
      }}
      
    >
      <Typography sx={{ px:2,py:1,display:'flex',cursor: 'pointer',
        alignItems:'center',
        '&:hover': {
          color: 'primary.main', 
          backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
        },}}
        onClick={handleNewChannelAction}
        >
          <Iconify icon={'uil:channel'} sx={{mr:1}}/>
          New channel
      </Typography>
      <Typography sx={{ px:2,py:1,display:'flex',cursor: 'pointer',
        alignItems:'center',
        '&:hover': {
          color: 'primary.main', 
          backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
        },}} 
        onClick={handleNotifsAction}
        >
          <Iconify icon={'mdi:notification-settings-outline'} sx={{mr:1}}/>
          Manage notifications
      </Typography>
      <Typography sx={{ px:2,py:1,display:'flex',cursor: 'pointer',
        alignItems:'center',
        '&:hover': {
          color: 'primary.main',
          backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
        },}} 
        onClick={handleAnonymityAction}
        >
          <Iconify icon={'mdi:anonymous'} sx={{mr:1}}/>
          Manage anonymity 
      </Typography>
        
        <Typography sx={{ px:2,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main',
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },}} 
          onClick={()=>{handleSettings()}}
          >
            <Iconify icon={'circum:settings'} sx={{mr:1}}/>
            Settings
        </Typography>
    </Popover>
);
  const renderSearchInput = (
    <ClickAwayListener onClickAway={handleClickAwaySearch}>
      <TextField
        fullWidth
        value={searchContacts.query}
        onChange={(event) => handleSearchContacts(event.target.value)}
        placeholder="Search contacts..."
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
            </InputAdornment>
          ),
        }}
        sx={{ mt: 0.5 ,ml: mdUp?1:-0,mr:!mdUp?12:0,
        }}
      />
    </ClickAwayListener>
  );
  
  const renderHead = (
    <>
    {!collapseDesktop?
    (<Box sx={{ width: '100%' ,height:mdUp?'100px':'auto'}} alignContent='flex-end'  >
      
      <BottomNavigation
        showLabels
        value={value}
        onChange={handleChange}
        sx={{
          // boxShadow: theme.customShadows.primary,
          borderBottom:'1px solid ',borderColor:'primary.main',
          pt:1,pb:1,mb:!mdUp?2:0,height: mdUp ? 1 : 'auto',

          }}

      >
         <BottomNavigationAction label="Direct" value="direct" icon={<Iconify icon='ri:message-3-line' width={20}/>} />
         <BottomNavigationAction label="Team" value='CHANNEL' icon={<Iconify icon='fluent:people-team-32-regular' width={20}/>} />
         <BottomNavigationAction label="Client" value='client' icon={<Iconify icon='solar:user-outline' width={20}/>} />
       </BottomNavigation>
    </Box>)
    :
    <>
      <Box sx={{ width: '100%' ,height:'5px',marginTop:2,marginBottom:-4}}  display="flex"
      alignItems="center" p={3}>
        <Tooltip title='New discussion'>
          <IconButton onClick={handleClickCompose} sx={{'&:hover,': {backgroundColor: 'transparent '},}} >
            <Iconify width={30} icon="solar:pen-new-square-outline" sx={{color:'inherit'}}/>
          </IconButton>
        </Tooltip>
      </Box>
    </>}
    </>
  );
        
  const renderContacts = (
    <>
      <ChatContacts>
        {!mdUp?
            <IconButton  
                size="small"
                sx={{zIndex:1,
                  mr:1.5,
                ...bgBlur({ opacity: 0.48, color: theme.palette.background.default }),
              }}
              onClick={handleCloseContacts}
              >
              <Iconify
                icon='eva:arrow-ios-back-fill'
                width={20}
              />
            </IconButton> : <></>}
      </ChatContacts>
    </>
  );
  
  const renderNewMesssage = (
    <>
      <ChatNewMessage>
        {!mdUp?
          <IconButton  
              size="small"
              sx={{zIndex:1,
                mr:1.5,
              ...bgBlur({ opacity: 0.48, color: theme.palette.background.default }),
            }}
            onClick={handleCloseNewDiscussion}
            >
            <Iconify
              icon='eva:arrow-ios-back-fill'
              width={20}
            />
          </IconButton> : <></>}
      </ChatNewMessage>
    </>
  );

  const renderContent = (
    <>

      <Stack direction="row" alignItems="flex-start" justifyContent="space-between" 
      sx={{mt:mdUp?1:0}} 
      >

        {!collapseDesktop && (
          <>
                <Box sx={{ml:2}}>
                  <ChatNavAccount />
                </Box>
           
            {/* <Box sx={{ flexGrow: 1 }} /> */}
            <Box>
            { 
              searchClicked ?  
              <Stack direction="row" alignItems="center" justifyContent="center" sx={{pb:0,}}>
                {renderSearchInput}
              </Stack> : 
              
              <Stack direction="row" alignItems="flex-end" justifyContent="flex-end" sx={{pb:2,mr:mdUp?-11:0}}>
                <Tooltip title='Search'><IconButton sx={{right: mdUp?-25:4,top:10}} onClick={handleSearch}><Iconify icon={'eva:search-fill'} sx={{pl:!mdUp?-5:0}} width={20}/></IconButton></Tooltip>
                <Tooltip title='Contacts'><IconButton sx={{right: mdUp?-25:4,top:10,backgroundColor:showContactsClicked ? (theme) => alpha(theme.palette.primary.lighter, 0.3):'',}} onClick={handleContactsAction}><Iconify icon={'fluent-mdl2:connect-contacts'} sx={{pl:!mdUp?-5:0}} width={20}/></IconButton></Tooltip>
                <Tooltip title='New discussion'><IconButton sx={{right: mdUp?-25:4,top:10,backgroundColor:newDiscussionClicked ? (theme) => alpha(theme.palette.primary.lighter, 0.3):'',}} onClick={handleNewDiscussionAction}><Iconify icon={'ri:chat-new-line'} sx={{pl:!mdUp?-5:0}} width={20}/></IconButton></Tooltip>
                <Tooltip title='Menu'><IconButton sx={{right: mdUp?-25:4,top:10,backgroundColor:showActions ? (theme) => alpha(theme.palette.primary.lighter, 0.3):'',}} onClick={handleActionsClick}><Iconify icon={showActions?'line-md:close-small':'circum:menu-kebab'} sx={{pl:!mdUp?-5:0}} width={20}/></IconButton></Tooltip>
              </Stack>
            }
            </Box>
          </>
        )}
        {
          mdUp &&
          <IconButton onClick={handleToggleNav} 
            size="small"
            sx={{zIndex:1,top:collapseDesktop?-15:-60,right:!collapseDesktop?-15:-80,border: `solid 1px ${theme.palette.divider}`,
            ...bgBlur({ opacity: 0.48, color: theme.palette.background.default }),
          }}
          >
            <Iconify
              icon={collapseDesktop ? 'eva:arrow-ios-forward-fill' : 'eva:arrow-ios-back-fill'}
              width={16}
            />
          </IconButton>
        }
        
      </Stack>

      {/* <Box sx={{ p: 2.5, pt: 0 }}>{!collapseDesktop && renderSearchInput}</Box> */}

      <Scrollbar sx={{ pb: 1 }}>
        {searchContacts.query && renderListResults}
        {showContactsClicked && renderContacts} 
        {/* {showSettingsClicked && renderSettings} */}
        {loading && renderSkeleton}
        {!mdUp && newDiscussionClicked && renderNewMesssage}
        {!searchContacts.query && !!conversations.allIds.length && !newDiscussionClicked && !showContactsClicked && renderList}
      </Scrollbar>
      {/* {!mdUp && showContactsClicked && renderContacts} */}
      <ChatNotifications onClose={()=>notifs.onFalse()} open={notifs.value}/>
      <ChatManageAnonymity onClose={()=>anonymity.onFalse()} open={anonymity.value}/>
      <ChatNewChannel onClose={()=>newChannel.onFalse()} open={newChannel.value}/>
    </>
  );


  return (
    <>      
      {mdUp ? (
        <Stack
          sx={{
            // position:'absolute',
            height: 1,
            flexShrink: 0,
            width: NAV_WIDTH,
            borderRight:`solid 1px ${theme.palette.divider}`,
            transition: theme.transitions.create(['width'], {
              duration: theme.transitions.duration.shorter,
            }),
            ...(collapseDesktop && {
              width: NAV_COLLAPSE_WIDTH,
            }),
          }}
        >
          {renderHead}
          {renderActions}
          
          {renderContent}
          
        </Stack>
      ) : (
        <>
          <Stack
          sx={{
            // position:'absolute',
            height: 1,
            flexShrink: 0,
            width: NAV_WIDTH,
            transition: theme.transitions.create(['width'], {
              duration: theme.transitions.duration.shorter,
            }),
            ...(collapseDesktop && {
              width: NAV_COLLAPSE_WIDTH,
            }),
          }}
        >
          {renderActions}
          {renderHead}

          {renderContent}
        </Stack>
        </>
      )}
    </>
  );
}
