'use client';

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

import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Container from '@mui/material/Container';

import { paths } from '@/routes/paths';
import { useBoolean, useCollapseNav, useResponsive, useRouter, useSearchParams } from '@/hooks';

import { useMockedUser } from '@/hooks/use-mocked-user';

import {useGetConversation } from '@/shared/api/chat javalin';

import { useSettingsContext } from '@/shared/components/settings';

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

import ChatRoom from '../chat-room';
import ChatMessageList from '../chat-message-list';
import ChatMessageInput from '../chat-message-input';
import ChatHeaderDetail from '../chat-header-detail';
import ChatHeaderCompose from '../chat-header-compose';
import {Button, IconButton,MenuItem,Popover,Typography,useTheme } from '@mui/material';

import Iconify from '@/shared/components/iconify';
import ChatNavGlobal from '../chat-nav-global';
import ChatNav from '../chat-nav';
import { bgBlur } from '@/shared/theme/css';
import { alpha } from '@mui/material/styles';
import React from 'react';
/* import { getParticipantDisplayInfo, updateConversationParticipants} from '@/utils/chatUtils'; */
import ChatAddToChannel from '../chat-add-to-channel';
import { ConfirmDialog } from '@/components/custom-dialog';
import { useGetContactsTest, useGetConversations } from '@/shared/api/chat javalin';

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

export default function MainView() {


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

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

  useEffect(() => {
    if (!mdUp) {
      onCloseMobile();
    }else{
      onCloseDesktop();
      onOpenMobile();
    }
  }, [onCloseDesktop, mdUp]);

  ///////////////////////////////////////
  
  const router = useRouter();

  const { user1 } = useMockedUser();

  const settings = useSettingsContext();

  const searchParams = useSearchParams();

  const [showChatRoom, setShowChatRoom] = useState(false);

  const [activateAnonymity, setActivateAnonymity] = useState(false);

  const [closeConversation,setCloseConversation] = useState(false);

  const selectedConversationId = searchParams.get('id') || '';

  const [selectedId,setSelectedId] = useState(`${selectedConversationId}`);

  const theme = useTheme();

  const anonymity = useBoolean();

  const confirmDelete = useBoolean();

  const confirmLeave = useBoolean();

  const confirmBlock = useBoolean();

  const [recipients, setRecipients] = useState<IClient[]>([]);

  const { contacts } = useGetContactsTest();

  const { conversations, conversationsLoading } = useGetConversations();

  // État pour stocker l'état des notifications pour chaque conversation
  const [notificationsState, setNotificationsState] = useState<{ [key: string]: boolean }>(() => {

    const initialNotificationsState: { [key: string]: boolean } = {};
    conversations.allIds.forEach((conversationId) => {
      initialNotificationsState[conversationId] = true;
    });

    return initialNotificationsState;
  });

  const { conversation, conversationError, conversationLoading} = useGetConversation(`${selectedConversationId}`);
 
  
  const [messages, setMessages] = useState<IChatMessage[]>([]);
  const [replyTo, setReplyTo] = useState<IChatMessage | null>(null); // State to track the message being replied to

  const handleReplyMessage = (message: IChatMessage | null) => {
    
    setReplyTo(message); // Set the message being replied to
  };

  // const handleNewMessage = (newMessage: IChatMessage) => {
  //   setMessages((prevMessages) => [...prevMessages, newMessage]);
  //   console.log("prv : "+ newMessage);
  // };

  useEffect(() => {
    if (conversation && conversation.messages) {
      setMessages(conversation.messages);
    }else{
      setMessages([]);
    }
  }, [conversation]);

  const handleNewMessage = useCallback((newMessage: IChatMessage) => {
    setMessages((prevMessages) => [...prevMessages, newMessage]);
  }, []);

  // Popover management for conversation actions

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

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

  ///

  const handleAnonymityAction = ()=>{
    handleClose();
    anonymity.onTrue();
  }
  /// Notif ///

  const [AnonymousState, setAnonymousState] = useState<{ [key: string]: boolean }>(() => {

    const initialState: { [key: string]: boolean } = {};
    if(conversations?.allIds)
    conversations.allIds.forEach((conversationId) => {
      initialState[conversationId] = true;
    });

    return initialState;
  });
  
  const handleCloseConversationClick = ()=>{
    handleClose();
    setCloseConversation(!closeConversation);
  }

  const handleAnonymityClick = ()=>{
    handleClose();
    setActivateAnonymity(!activateAnonymity);
  }
  ///
   /// Anonymity ///
  const handleAnonymousClick = ()=>{
    toggleAnonymous(selectedConversationId);
  }
  ///
  // Activer ou désactiver les notifications pour une conversation
  const toggleAnonymous = (conversationId: string) => {
    setAnonymousState((prevAnonymousState) => ({
      ...prevAnonymousState,
      [conversationId]: !prevAnonymousState[conversationId], // Inverse l'état des notifications pour cette conversation
    }));
  };

  /////////
  /// Notif ///

  const handleNotificationClick = ()=>{
    toggleNotifications(selectedConversationId);
  }
  ///
  // Activer ou désactiver les notifications pour une conversation
  const toggleNotifications = (conversationId: string) => {
    setNotificationsState((prevNotificationsState) => ({
      ...prevNotificationsState,
      [conversationId]: !prevNotificationsState[conversationId], // Inverse l'état des notifications pour cette conversation
    }));
  };

  /////////
 
 /*  const participants: IClient[] = conversation //CHANGES
    ? conversation.participants
    : []; */
    const participants: IClient[]  = conversation && !conversationLoading
    ? conversation.participants
    : [];

  


  useEffect(() => {
    if (conversationError || !selectedConversationId) {
      router.push(paths.dashboard.chat);
    }
  }, [conversationError, router, selectedConversationId]);

  useEffect(() => {
    // Cette fonction s'exécute à chaque fois que l'URL change.
    const newSelectedId = searchParams.get('id') || '';
    setSelectedId(newSelectedId);
  }, [searchParams]); //

  const handleAddRecipients = useCallback((selected: IClient[]) => {
    setRecipients(selected);
  }, []);

  const handleToggleChatRoom = ()=>{
    setShowChatRoom(!showChatRoom);
    handleClose();
  }
  const handleReturnButtonClick = () => {
     
    //Ce code permet de supprimer le 'id' de conversation selectionnee de l'URL pour retourner à la vue d'ensemble des conversations
      const url = new URL(window.location.href);
      url.searchParams.delete('id');
      window.history.pushState({}, '', url);
      setSelectedId('');
  };
  
  
  const details = !!conversation;
  const renderconversationActions = (
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        PaperProps={{
          sx:{border:(theme) => `solid 2px ${theme.palette.divider}`,
            marginTop:3,
             width:250},
        }}
        
      >
        <Typography sx={{px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main',
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },
          }}
          onClick={handleToggleChatRoom}
          
          >
            <Iconify icon={'octicon:info-24'} sx={{mr:1}}/>
          Infos
        </Typography>
        <Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main', 
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },}}
          onClick={()=>{handleClose();handleReturnButtonClick();}}
          >
            <Iconify icon={'carbon:close-outline'} sx={{mr:1}}/>
          Close conversation
        </Typography>
        {!mdUp && <Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main',
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },}} 
          onClick={()=>{handleClose()}}
          >
            <Iconify icon={'eva:search-fill'} sx={{mr:1}}/>
          Search 
          </Typography>}
          {selectedId!='' && conversations.byId[selectedConversationId]?.typeConv!='CHANNEL'?
          <Typography sx={{ px:1,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={'gg:add'} sx={{mr:1}}/>
            Add to a channel
          </Typography>:<></>
          }
          {conversation?.typeConv==='GROUP'&&<Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main',
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },}} 
          onClick={handleAnonymityClick}
          >
            <Iconify icon={activateAnonymity?'mdi:anonymous-off':'mdi:anonymous'} sx={{mr:1}}/>
          {!activateAnonymity?'Active anonymity':'Desactivate anonymity'}
        </Typography>}
        {selectedId!='' && conversations.byId[selectedConversationId]?.typeConv==='CHANNEL'?
          <Typography sx={{ px:1,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={'gg:add'} sx={{mr:1}}/>
            Add members
          </Typography>:<></>
          }
        <Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          '&:hover': {
            color: 'primary.main',
            backgroundColor:(theme) => alpha(theme.palette.primary.main, 0.1),
          },}} 
          onClick={()=>{confirmDelete.onTrue();handleClose()}}
          >
            <Iconify icon={'fluent:delete-32-regular'} sx={{mr:1}}/>
          Delete conversation
        </Typography>
        {conversations.byId[selectedConversationId]?.typeConv!='CHANNEL'?
          <Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
            alignItems:'center',
            color:(theme) => alpha(theme.palette.error.main, 0.9),
            '&:hover': {
              backgroundColor:(theme) => alpha(theme.palette.error.main, 0.1),
            },}} 
            onClick={()=>{confirmBlock.onTrue();handleClose()}}
          
            >
              <Iconify icon={'gg:block'} sx={{mr:1}}/>
            Block user
          </Typography>:
          <Typography sx={{ px:1,py:1,display:'flex',cursor: 'pointer',
          alignItems:'center',
          color:(theme) => alpha(theme.palette.error.main, 0.9),
          '&:hover': {
            backgroundColor:(theme) => alpha(theme.palette.error.main, 0.1),
          },}} 
          onClick={()=>{confirmLeave.onTrue();handleClose()}}
        
          >
              <Iconify icon={'pepicons-pencil:leave'} sx={{mr:1}}/>
              Leave channel
          </Typography>
        }
      </Popover>
  );
  const renderHead = (
    <Stack
      direction="row"
      alignItems="center"
      flexShrink={0}
      sx={{ pr: 1, pl: !mdUp?0.5:2.5, py: 1, minHeight: 72 }}
    >
      {!mdUp?
        <IconButton  
            size="small"
            sx={{zIndex:1,
              mr:0.5,
            ...bgBlur({ opacity: 0.48, color: theme.palette.background.default }),
          }}
          onClick={handleReturnButtonClick}
          >
          <Iconify
            icon='eva:arrow-ios-back-fill'
            width={25}
          />
        </IconButton> : <></>}
      {selectedConversationId ? (
        <>{details && <ChatHeaderDetail participants={participants} selectedId={selectedConversationId} conversation={conversations.byId[selectedConversationId]}>
            { !mdUp && 
            <>
            
              <IconButton onClick={handleNotificationClick}>
                <Iconify icon={notificationsState[selectedConversationId]?"mdi:notifications":"mdi:notifications-off"} />
              </IconButton>
              <IconButton>
                <Iconify icon="solar:phone-bold" />
              </IconButton>
              <IconButton>
                <Iconify icon="solar:videocamera-record-bold" />
              </IconButton>
          </>}
            {
              mdUp && 
              <>
                <IconButton>
                  <Iconify icon="ic:round-search" />
                </IconButton>
                <IconButton onClick={handleNotificationClick}>
                  <Iconify icon={notificationsState[selectedConversationId]?"mdi:notifications":"mdi:notifications-off"} />
                </IconButton>
              </>
            }
            
            <IconButton onClick={handleClick} aria-describedby={id}>
              <Iconify icon="eva:more-vertical-fill" />
            </IconButton>
          </ChatHeaderDetail>}</>
      ) : (
        <ChatHeaderCompose  onAddRecipients={handleAddRecipients} >
           <Typography variant="subtitle2" sx={{ color: 'text.primary', mr: 2 }}>
            To :
          </Typography>
        </ChatHeaderCompose>
      )}
    </Stack>
  );
  
  const renderNav = (
    <ChatNav
      contacts={contacts}
      // conversations={updateConversationsWithParticipants(conversations,activateAnonymity)}
      conversations={conversations}
      loading={conversationsLoading}
      selectedConversationId={selectedConversationId} 
      />
      
  );

  const renderAddToChannel = (
    <ChatAddToChannel onClose={()=>anonymity.onFalse()} open={anonymity.value} type={conversations.byId[selectedConversationId]?.typeConv}/>
  );
  
  const renderDeleteConversation = (
    <ConfirmDialog
          open={confirmDelete.value}
          onClose={confirmDelete.onFalse}
          title="Delete conversation"
          content="Are you sure want to delete this conversation ?"
          action={
            <Button variant="contained" color="error" onClick={confirmDelete.onFalse}>
              Delete
            </Button>
          }
     />
  );
  const renderLeaveChannel = (
    <ConfirmDialog
          open={confirmLeave.value}
          onClose={confirmLeave.onFalse}
          title="Leave channel"
          content="Are you sure want to leave this channel ?"
          action={
            <Button variant="contained" color="error" onClick={confirmDelete.onFalse}>
              Leave
            </Button>
          }
     />
  );
  const renderBlocksUsers = (
    <ConfirmDialog
          open={confirmBlock.value}
          onClose={confirmBlock.onFalse}
          title={`Block User`}
          content="Are you sure want to block this user ?"
          action={
            <Button variant="contained" color="error" onClick={confirmDelete.onFalse}>
              Block
            </Button>
          }
     />
  );
  const renderMessages = (
    
    <Stack
      sx={{
        width: 1,
        height: 1,
        overflow: 'hidden',
      }}
    >
      {/* {participants.length>1 && <ChatMessageList messages={conversation?.messages} participants={participants} />} */}
      {<ChatMessageList messages={[...messages].sort((a:IChatMessage, b:IChatMessage) => a.id - b.id)} participants={participants} selectedConversationid={selectedConversationId}  onReplyMessage={handleReplyMessage} replyMessage={replyTo}/>}

      {/* <ChatMessageList messages={conversation?.messages} participants={(conversation?.type==='GROUP')?participants.map((participant) => getParticipantDisplayInfo(participant, activateAnonymity)):participants} /> */}
      
      <ChatMessageInput
        recipients={recipients}
        onAddRecipients={handleAddRecipients}
        onNewMessage={handleNewMessage}
        selectedConversationId={selectedConversationId}
        disabled={!recipients?.length && !selectedConversationId}
        replyTo={replyTo} // Pass the replyTo state to ChatMessageInput
        onClearReply={() => setReplyTo(null)}
      />
    </Stack>
    
  );
  // {console.log("selectId : "+selectedId);
  //   // confirm(participants[0].firstname)
  // }

  return !mdUp && !collapseDesktop? (
      <Container sx={{ width: '100%', maxWidth: '100%', p: 0,position:'fixed'}}>
        <ChatNavGlobal 
          contacts={contacts}
          conversations={conversations}
          loading={conversationsLoading}
          selectedConversationId={selectedConversationId}
        />
  
        <Stack direction="row" sx={{ height: 'calc(100vh - 150px)' }}>   
          {selectedId!==''?
              <Stack sx={{ width: 1, height: 1, overflow: 'hidden' }}>
              {!showChatRoom && renderHead}
    
              <Stack
                direction="row"
                sx={{
                  width: 1,
                  height: 1,
                  overflow: 'hidden',
                  borderTop: (theme) => `solid 1px ${theme.palette.divider}`,
                }}
              >
                {renderconversationActions}

                {showChatRoom ?
                  (
                    showChatRoom && 
                    <ChatRoom conversation={conversation} participants={participants} >
                        <IconButton onClick={handleToggleChatRoom} sx={{ ml: 1.5, my: 1.5,mr:2 }}><Iconify width={16} icon="mingcute:close-fill" /></IconButton>
                    </ChatRoom>

                  ):
                  renderMessages
                }
              </Stack>
            </Stack> :
            renderNav
          }
        </Stack>
        {renderLeaveChannel}
        {renderDeleteConversation}
        {renderBlocksUsers}
        {renderAddToChannel}
        
      </Container>
    
  ) : (

    <Container maxWidth={settings.themeStretch ? false : 'xl'} >
  
        <ChatNavGlobal 
          contacts={contacts}
          conversations={conversations}
          loading={conversationsLoading}
          selectedConversationId={selectedConversationId}
        />
  
        <Stack component={Card} direction="row" sx={{ height: '72vh' }}>
          {renderNav}
          {(openMobile ?<Stack
            sx={{
              width: 1,
              height: 1,
              overflow: 'hidden',
            }}
            
            
          >
            {renderHead}
  
            <Stack
              direction="row"
              sx={{
                width: 1,
                height: 1,
                overflow: 'hidden',
                borderTop: (theme) => `solid 1px ${theme.palette.divider}`,
              }}
            >
              {renderconversationActions}
              {renderDeleteConversation}
              {renderLeaveChannel}
              {renderBlocksUsers}
              
              {renderMessages}
              {renderAddToChannel}
              {renderAddToChannel}
              {showChatRoom && 
              <ChatRoom conversation={conversation} participants={participants} >
                  <IconButton onClick={handleToggleChatRoom} sx={{ ml: 1.5, my: 1.5,mr:2 }}><Iconify width={16} icon="mingcute:close-fill" /></IconButton>  
              </ChatRoom>}
            </Stack>
          </Stack> : <>          
          </>)}
          
        </Stack>
      </Container>
  );
}
