import { formatDistanceToNowStrict } from 'date-fns';

import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Avatar from '@mui/material/Avatar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';

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

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

import { IChatMessage, IChatParticipant, IClient, IReactions } from '@/shared/types/chat';
import { alpha } from '@mui/material/styles';
import { useRouter } from 'next/router';

import { useBoolean, useGetMessage } from '@/hooks';
import { Button, ButtonBase, Chip, InputBase, Popover, TextField, Tooltip } from '@mui/material';
import { ConfirmDialog } from '@/components/custom-dialog';
import { forwardRef, SetStateAction, useCallback, useEffect, useState } from 'react';
import { deleteMessage, editMessage, mutateConversationInreact, pinMessage, reactToMessage } from '@/shared/api/chatv2';
import EmojiPicker from '@/shared/components/emoji/EmojiPicker';
import { EmojiClickData } from 'emoji-picker-react';
import { mutate } from 'swr';
import { useGetConversation } from '@/shared/api/chat javalin';
import ChatTransferDialog from './chat-transfer-dialog';

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

type Props = {
  message: IChatMessage;
  participants: IClient[];
  selectedConversationId : string;
  onOpenLightbox: (value: string) => void;
  onPinMessage: (message: IChatMessage) => void;
  onReplyMessage: (message: IChatMessage) => void;
};

const ChatMessageItem = forwardRef<HTMLDivElement, Props>(({ message, participants,selectedConversationId, onOpenLightbox,onPinMessage,onReplyMessage}, ref) => {

  const { user1 } = useMockedUser();

  const { me, senderDetails, hasImage } = useGetMessage({
    message,
    participants,
    currentUserId: `${user1?.id}`,
  });

  const { firstName, avatarUrl } = senderDetails;

  const { body, createdAt,reactions,replyTo } = message;

  const [messageUp, setMessageUp] = useState(body);

  const [showPicker, setShowPicker] = useState(false);

  const [isEdited, setIsEdited] = useState(false);

  const messageUpdated = messageUp!==body;

  const [update, setUpdate] = useState(false);

  const [reactionss, setReactions] = useState<string[]>(reactions?.map((reaction:IReactions)=>reaction.emoji) || []);

  const contact = useMockedUser();

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const openDialog = useBoolean();

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


  // const handlePinMessage = useCallback(async () => {
  //   try {
  //     const updatedMessage = await pinMessage(message.uuid);
  //     // mutate(`/api/messages/pin/${message.conversation.uuid}`);
  //     onPinMessage(updatedMessage);
  //   } catch (error) {
  //     console.error('Failed to pin/unpin message:', error);
  //   }
  // }, [message, onPinMessage]);

  const handlePinMessage = useCallback(async () => {
    await pinMessage(message.uuid);
    onPinMessage({ ...message, pined: !message.pined });
    mutate(`http://localhost:4000/conversation/${selectedConversationId}`)
    console.log('Pined message : ',message)
  }, [selectedConversationId, message, onPinMessage]);

  const handleShareMessage = () => {
    
  }

  const handleDeleteMessage = useCallback(async () => {
    try {
      const updatedMessage = await deleteMessage(message.uuid, selectedConversationId);
    } catch (error) {
      console.error('Failed to delete message:', error);
    }
  }, [message]);
  
  const handleUpdateMessage = useCallback(async () => {
    message.body =messageUp;
    message.update= true;
    try {
      // const idconv = Arraysid!=null ?id : '';
      await editMessage(message);
      setUpdate(false);
    } catch (error) {
      console.error('Failed to delete message:', error);
    }
  }, [message]);
  

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);

  const handleInputChange = (event: { target: { value: SetStateAction<string>; }; }) => {
    setMessageUp(event.target.value);
  };
  
  const handleUpdateCliqued = ()=>{
    setUpdate(true);
  }
  
  const renderInfo = (
    <Typography
      noWrap
      variant="caption"
      sx={{
        mb: 1,
        color: 'text.disabled',
        ...(!me && {
          mr: 'auto',
        }),
      }}
    >
      {!me && `${firstName},`} &nbsp;
      {formatDistanceToNowStrict(new Date(message.date), {
        addSuffix: true,
      })}
    </Typography>
  );
  const handleSave = async () => {
    message.body =messageUp;
    message.update= true;

    if (message) {
        await editMessage(message);
        setUpdate(false);
    }
  };
  
  const handleEmojiClick = (emojiData: EmojiClickData) => {
    handleShowEmojis(emojiData.emoji)
    setReactions((prev) => [...prev, emojiData.emoji]);
    setShowPicker(false);
  };

  const handleShowEmoji = () => {
    setShowPicker(!showPicker);
  };
  
  const handleShowEmojis = useCallback(async (emoji: string) => {
    try {
      const updatedMessage = await reactToMessage(message.uuid, contact.user1.uuid, emoji,selectedConversationId);
      // mutate(`/messages/${message.uuid}`, updatedMessage, false);
    } catch (error) {
      console.error('Failed to react to message:', error);
    }
  }, [message]);

  const handleRemoveReaction = (index: number) => {
    setReactions(prevReactions => prevReactions.filter((_, i) => i !== index));
  };
    
    const renderAllreaction = (
      <Stack spacing={0}>
        <>
          {reactionss.map((emoji,index) => (
              <Avatar sx={{background:'transparent',fontSize: '0.9rem',width:20,height:20,}} key={index} onClick={()=>handleRemoveReaction(index)}>
                    {emoji}
              </Avatar>
              ))}
        </>
      </Stack>
    );
  
    const renderReactions = (
    
      <Chip avatar={
          <>
          {reactionss.slice(0, 2).map((emoji, index) => (
              <Avatar sx={{background:'transparent',fontSize: '0.9rem',mr:0,width:20,height:20,}} key={index}>
                    {emoji}
              </Avatar>
              ))}
          </>
        } 
        sx={{ mt:-1,py:1.3,zIndex:11,background:(theme) => alpha(theme.palette.grey[300], 1),borderRadius: 2,height:20,mr:'85%'}}
        size='small'
        variant='filled'
        label={<Typography variant="body2" sx={{ fontSize: '0.8rem' ,color:'black'}}>
              {reactionss.length}
            </Typography>}
        onClick={handleChipClick}
      />
    );
    
    useEffect(() => {
      // Mettre à jour l'état local des réactions si le message change
      setReactions(message.reactions?.map((reaction: IReactions) => reaction.emoji) || []);
    }, [message]); 
    
  const renderModifMessage = (
    <>
      <InputBase
        value={messageUp}              
        onChange={handleInputChange} 
        sx={{
          minWidth: 300,
          maxWidth: 320,
          p:0,
          borderRadius: 1,
          typography: 'body2',
          position: 'relative', 
        }}
        fullWidth
        multiline
        
      />
      <Stack justifyContent='flex-end' direction='row' spacing={1} mt={1}>
        <Button variant="soft" sx={{ backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.3),}} onClick={()=>{setUpdate(false);setMessageUp(messageUp);handleSave()}}>
          Send
          <Iconify icon="carbon:send-alt" width={16} ml={0.5}/>
        </Button>
        <Button variant="soft" color="error" onClick={()=>setUpdate(false)}>
          Cancel
        </Button>
      </Stack>
    </>
  );
  
  useEffect(() => {
    // Mettre à jour l'état du message lorsque le message change
    setMessageUp(message.body);
    setIsEdited(message.update);
  }, [message.body, message.update]);
  
  const renderBody = (
    <>

    <Stack
    id={`${message.id}`}
      sx={{
        p: 1.5,
        minWidth: 48,
        maxWidth: 320,
        borderRadius: 1,
        typography: 'body2',
        bgcolor: 'background.neutral',
        ...(me && {
          color: 'grey.800',
          bgcolor: 'primary.lighter',
        }),
        ...(hasImage && {
          p: 0,
          bgcolor: 'transparent',
        }),
        position: 'relative', // Ajoutez cette ligne pour rendre la position relative
      }}
    >
         
      {hasImage ? (
        <Box>
          <IconButton
            className="message-actions"
            size="small"
            sx={{
              position: 'absolute',
              opacity:0,
              top: -8,
              ...(!me && {
                right: -30,
              }),
              ...(me && {
                left: -30,
              }),
              transition: (theme) =>
                theme.transitions.create(['opacity'], {
                duration: theme.transitions.duration.shorter,
                
              }),
            }}
            onClick={() => onReplyMessage(message)}
          >
            <Tooltip title='Replay'>
              <Iconify icon="solar:reply-bold" width={18} />
            </Tooltip>
          </IconButton>
          <Box
            component="img"
            alt="attachment"
            src={body}
            onClick={() => onOpenLightbox(body)}
            sx={{
              minHeight: 220,
              borderRadius: 1.5,
              cursor: 'pointer',
              '&:hover': {
                opacity: 0.9,
              },
            }}
          />
        </Box>
      ) : (
        <Box>
          
          <IconButton
            className="message-actions"
            size="small"
            sx={{
              position: 'absolute',
              opacity: 0,
              top: -8,
              ...(!me && {
                right: -30,
              }),
              ...(me && {
                left: -30,
              }),
              transition: (theme) =>
                theme.transitions.create(['opacity'], {
                duration: theme.transitions.duration.shorter,
                
              }),
            }}
            onClick={() => onReplyMessage(message)}
          >
            {!update &&
              <Tooltip title='Replay'>
                <Iconify icon="solar:reply-bold" width={18} />
              </Tooltip>
            }
            
          </IconButton>
            <Typography >
            {update && me ? renderModifMessage : messageUp}

           </Typography>
          
          {isEdited &&
                <Typography
                  noWrap
                  variant="caption"
                  sx={{
                    mb: 1,
                    color: 'text.disabled',
                    ml:1
                  }}      
                >
                    (Edited)
                </Typography>
            }
        </Box>
      )}
    </Stack></>
  );
  const renderActions = (
    <Stack
      direction="row"
      className="message-actions"
      sx={{
        pt: 0.5,
        opacity: 0,
        top: '100%',
        left: 0,
        position: 'absolute',
        transition: (theme) =>
          theme.transitions.create(['opacity'], {
            duration: theme.transitions.duration.shorter,
          }),
        ...(me && {
          left: 'unset',
          right: 0,
        }),
      }}
    >
      {me &&
      <IconButton size="small" onClick={handleUpdateCliqued}>
        <Tooltip title='Edit the message'>
          <Iconify icon="streamline:chat-bubble-square-write" width={16} />
        </Tooltip>
      </IconButton>
      }
      <IconButton size="small" onClick={handleShowEmoji}>
        <Tooltip title='React'>
          <Iconify icon="eva:smiling-face-fill" width={16} />
        </Tooltip>
      </IconButton>
      <IconButton size="small" onClick={handlePinMessage} >
        <Tooltip title='Pin'>
          <Iconify icon="fluent-mdl2:pinned" width={16} />
        </Tooltip>
      </IconButton>
      <IconButton size="small" onClick={openDialog.onToggle} sx={{left:0}}   >
        <Tooltip title='Share'>
          <Iconify icon="carbon:send-alt" width={16} />
        </Tooltip>
      </IconButton>
      {me && <IconButton size="small" onClick={handleDeleteMessage}>
        <Tooltip title='Delete'>
          <Iconify icon="solar:trash-bin-trash-bold" width={16} />
        </Tooltip>
      </IconButton>}
      {openDialog.value && (

      <ChatTransferDialog isOpen={openDialog} onClose={openDialog.onFalse} message={message} />

      )}
    </Stack>
  );
  
  // const renderReactions = (
  //   <Stack direction="row" spacing={0} mt={-1} sx={{zIndex:11}}>
  //     {reactionss.map((emoji, index) => (
  //       <Typography key={index} variant="body2" sx={{ fontSize: '0.8rem' }}>
  //         {emoji}
  //       </Typography>
  //     ))}
  //   </Stack>
  // );


  const handleScrollToMessage = (messageId: string) => {
    const element = document.getElementById(messageId);
    if (element) {
      // Temporarily scroll up a bit to ensure the element can be scrolled back into view
      window.scrollBy(0, -1);
  
      setTimeout(() => {
        // Scroll the element back into view
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 50); // Short delay to ensure the initial scroll takes effect
    }
  };
  return (
    <>    
      { message.replyTo && <ButtonBase 
      onClick={() => handleScrollToMessage(message.replyTo ? message.replyTo.id.toString() : '')} 
      sx={{ 
        width: '100%', 
        textAlign: me ? 'right' : 'left', 
        display: 'block', 
        marginLeft: me ? 'auto' : 'inherit', 
        ml: me ? 0 : 4, 
        mb: 1 
      }}
    >
      <Typography variant="caption" sx={{ width: '100%' }}>
        <Iconify icon="solar:reply-bold" width={18} />
        <strong>Reply to: </strong>
        {message.replyTo.body.slice(0, 35)}...
      </Typography>
    </ButtonBase> 
      }
         
    <Stack ref={ref} direction="row" justifyContent={me ? 'flex-end' : 'unset'} sx={{ mb: 5 }}>
      {!me && <Avatar alt={firstName} src={avatarUrl} sx={{ width: 32, height: 32, mr: 2 }} />}

      <Stack alignItems="flex-end">
        {renderInfo}

        <Stack
          direction="row"
          alignItems="center"
          sx={{
            position: 'relative',
            '&:hover': {
              '& .message-actions': {
                opacity: 1,
              },
            },
          }}
        > 
          {renderBody}
          {!update && renderActions}
          
        </Stack>
        {/* {renderReactions} */}
        {reactionss?.length>0 && renderReactions}
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'center',
          }}
      >
        {renderAllreaction}
      </Popover>
        <Stack sx={{mt:4}}>
          {showPicker && (
              <EmojiPicker onEmojiClick={handleEmojiClick} />
            )}
            
        </Stack>
      </Stack>
    </Stack>
    </>
  );
})
export default ChatMessageItem;