import Box from '@mui/material/Box';

import Scrollbar from '@/shared/components/scrollbar';
import Lightbox, { useLightBox } from '@/shared/components/lightbox';
import { alpha } from '@mui/material/styles';
import { IChatMessage, IChatParticipant, IClient } from '@/shared/types/chat';

import { useAuthContext, useMessagesScroll } from '@/hooks';
import ChatMessageItem from './chat-message-item';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Stack, Tooltip, Typography } from '@mui/material';
import Iconify from '@/shared/components/iconify';
import { m } from 'framer-motion';
import ChatMessagesPinned from './chat-messages-pinned';
import ChatReplyMessage from './chat-reply-message';
import { pinMessage } from '@/shared/api/chatv2';
import { mutate } from 'swr';

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

type Props = {
  messages: IChatMessage[];
  participants: IClient[];
  selectedConversationid : string;
  onReplyMessage: (message: IChatMessage | null) => void;
  replyMessage:IChatMessage | null;
};

export default function ChatMessageList({ messages = [], participants,selectedConversationid='', onReplyMessage,replyMessage }: Props) {

  const {user} = useAuthContext();

 /*  const initialMessage: IChatMessage = {
    id: 1,
    uuid: '',
    body: '',
    createdAt: new Date(),
    date : new Date(),
    destinationUuid : '',
    pined : false,
    owner : participants[0],
    reactions : [],
    // sourceUuid : '',
    type : '',
    update: false,
    conversation: '',
    replyTo: null
    
  }; */

  const [messagesList, setMessagesList] = useState<IChatMessage[]>(messages);

/*   const [replyMessage, setReplyMessage] = useState<IChatMessage>(initialMessage);
 */
  const { messagesEndRef} = useMessagesScroll(messages);

  const messageRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  const handleScrollToMessage = (messageId: string) => {
    const element = messageRefs.current[messageId];
    
    if (element) {
      
      element.scrollIntoView({ behavior: 'smooth' });
    }
  };

  const [expanded, setExpanded] = useState(false);

  const handleBoxClick = () => {
    setExpanded(true);
  };
  const handleBoxClose = () => {
    setExpanded(false);
  };

  const handleScrollToMessageWithClose = async (messageId: string) => {
    // Fermer l'expansion
    handleBoxClose();
    
    // Attendre un peu pour que la fermeture soit effective 
    await new Promise(resolve => setTimeout(resolve, 200)); // Attendre 200ms
  
    // Dérouler vers le message
    handleScrollToMessage(messageId);
  };

  const [pinnedMessages, setPinnedMessages] = useState<IChatMessage[]>((messages?.filter((message) => {message.conversation===selectedConversationid && message.pined})) || []);
  useEffect(() => {
    setPinnedMessages(messages.filter((message) => message.pined));
    // console.log('pinnedMessages length : ',pinnedMessages.length)
  }, [messages]);

  const handleRemovePinnedMessage = (index: number) => {
    setPinnedMessages(prev => prev.filter((_, i) => i !== index));
  };

  const handlePinMessage = (message: IChatMessage) => {
    setPinnedMessages(prev => [...prev, message]);
    // console.log('pinnedMessages length : ',pinnedMessages.length)
  };
  
  const handleDeleteMessage = useCallback((messageUuid: string) => {
    setMessagesList(prev => prev.filter((message) => message.uuid !== messageUuid));
  }, []);

  const handleUnPinMessage = useCallback(async (message:IChatMessage) => {
    await pinMessage(message.uuid);
    mutate(`http://localhost:4000/conversation/${selectedConversationid}`)
    console.log('Pined message : ',message)
  }, [pinnedMessages]);
  
  // useEffect(() => {
  //   setPinnedMessages(messages.filter((message) => message.pined === true));
  // }, [messages]);

  const pined = messages.filter((message) => message.pined === true)

  // const handleRemovePinnedMessage = (index: number) => {
  //   setPinnedMessages(prevPinnedMsgs => prevPinnedMsgs.filter((_, i) => i !== index));
  // };

  // const handlePinMessage = (message: IChatMessage) => {
  //   setPinnedMessages(prevPinnedMsgs => [...prevPinnedMsgs,message]);
    
  // };

  // const handleDeleteMessage = useCallback((messageUuid: string) => {
  //  messages = messages.filter((message) => message.uuid !== messageUuid);
  // }, []);

  //Pour repondre a un message

  


  
  // const handleRemoveReplyMessage = () => {
  //   setReplyMessage(null);
  // };

  const slides = messages
    .filter((message) => message.type === 'image')
    .map((message) => ({ src: message.body }));
  
  const lightbox = useLightBox(slides);

  const renderPinnedMessages = () =>
    {messages.length>0 && (
      <Scrollbar sx={{ px: 3, py: 5, height: 1 }}>
        <Box sx={{ mb: 2 }}>
          {messages.map((message) => (
            <> <ChatMessageItem
            key={message.id}
            message={message}
            participants={participants}
            onOpenLightbox={() => lightbox.onOpen(message.body)}
            onPinMessage={() => {}}
            selectedConversationId={selectedConversationid}
            onReplyMessage={() => {}}

          />
          </>
           
          ))}
        </Box>
      </Scrollbar>
    )}
    
    const pin = (
      <Box sx={{background:(theme) => alpha(theme.palette.grey[400], 0.58),
        position: 'relative',
        borderTopLeftRadius: 10,
        borderBottomLeftRadius: 10,
        height:40,
        width:40,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        ml:'auto',
        mb:-8,
        py:1,
        // flexShrink: 0  
        zIndex:111
        }}
        component={m.div}
        
        initial={{ width: 40,height:40 }}
        animate={{ width: expanded ? '100%' : 40,height: expanded ? '70%' : 40,}}
        transition={{ duration: 0.3 }}
        >
          {!expanded ? <Iconify icon="fluent-mdl2:pinned" width={16} sx={{cursor: 'pointer',}} onClick={handleBoxClick}/> :
            <>
            
            <Iconify icon="streamline:delete-1-solid" width={10}  sx={{
                    position: 'absolute', // Positionner l'icône en haut à droite
                    top: 8, // Ajustez la position verticale
                    left: 8, // Ajustez la position horizontale
                    cursor: 'pointer',
                    zIndex:1111
                  }} onClick={handleBoxClose} />
            <Typography variant="subtitle2" sx={{position: 'absolute',top:2,zIndex:1111}}>Pinned Messages</Typography>
            <Scrollbar sx={{ px: 3, py: 5, height: 1 }}>
              <Stack direction="column" spacing={2} alignItems={'flex-start'} >
                
                  {pinnedMessages.length > 0 ? (
                      // <Box key={index} sx={{ p: 1, bgcolor: 'background.neutral', borderRadius: 1 }}>
                      //   <Typography variant="body2">{message.body} </Typography>
                       
                      // </Box>
                      <Box sx={{ mb: 2 }}>
                        {pinnedMessages.map((message,index) => (
                          <ChatMessagesPinned
                            key={message.uuid}
                            message={message}
                            participants={participants}
                            onOpenLightbox={() => lightbox.onOpen(message.body)}
                            onClick={handleScrollToMessageWithClose}
                      
                          >
                            <Tooltip title='unpin'>
                              <Iconify icon="fluent-mdl2:unpin" width={16} sx={{color:'grey.800'}} onClick={()=>handleUnPinMessage(message)}/>
                            </Tooltip>
                          </ChatMessagesPinned>
                        ))}
                      </Box>
                  ) : (
                    <Typography variant="body2">No pinned messages.</Typography>
                  )}
              </Stack>
            </Scrollbar>
            </>
          }
        </Box>
    );

  return (
    <>
      {messages?.length>0 ? pin : <></>}
      <Scrollbar ref={messagesEndRef} sx={{ px: 3, py: 5,pb:0, height: 1 }}>
        <Box>
          {messages.map((message,index) => (
            <>
            
            <ChatMessageItem
              key={index}
              message={message}
              participants={participants}
              selectedConversationId= {selectedConversationid}
              onOpenLightbox={() => lightbox.onOpen(message.body)}
              ref={(el) => {
                messageRefs.current[message.uuid] = el;
              }}
              onPinMessage={handlePinMessage}
              onReplyMessage={onReplyMessage}
            /></>
          ))}
        </Box>
      </Scrollbar>
      {replyMessage && replyMessage.uuid != '' ? 
        <ChatReplyMessage 
          key={replyMessage!.id}
          message={replyMessage}
          participants={participants}
          onOpenLightbox={() => lightbox.onOpen(replyMessage!.body)}
          onClick={handleScrollToMessageWithClose}
          onCloseReply={()=>onReplyMessage(null)}
          >
          </ChatReplyMessage> 
          : <></>}

      <Lightbox
        index={lightbox.selected}
        slides={slides}
        open={lightbox.open}
        close={lightbox.onClose}
      />
    </>
  );
}
