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 } from '@/shared/types/chat';
import { alpha } from '@mui/material/styles';

import { useBoolean, useGetMessage } from '@/hooks';
import { Button, Chip, InputBase, Popover, TextField, Tooltip } from '@mui/material';
import { ConfirmDialog } from '@/components/custom-dialog';
import { SetStateAction, useState } from 'react';
import { EmojiClickData } from 'emoji-picker-react';
import CustomEmojiPicker from '@/shared/components/emoji/EmojiPicker';
import EmojiPicker from '@/shared/components/emoji/EmojiPicker';
import theme from '@/shared/theme';

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

type Props = {
  message: IChatMessage;
  participants: IClient[];
  onOpenLightbox: (value: string) => void;
  onClick?: (messageId: string) => void;
  children: React.ReactNode;
};

export default function ChatMessagesPinned({ message, participants, onOpenLightbox ,onClick,children}: Props) {

  const { user1 } = useMockedUser();

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

  const { firstName, avatarUrl } = senderDetails;

  const { body, createdAt } = message;

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

  const messageUpdated = messageUp!==body;

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

  const [reactions, setReactions] = useState<string[]>([]);

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

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

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

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

  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  const handleInputChange = (event: { target: { value: SetStateAction<string>; }; }) => {
    setMessageUp(event.target.value);
  };

  const handleEmojiClick = (emojiData: EmojiClickData) => {
    setReactions((prev) => [...prev, emojiData.emoji]);
    setShowPicker(false);
  };
  

  const renderInfo = (
    <Typography
      noWrap
      variant="caption"
      sx={{
        mb: 1,
        color: 'grey.600',
        mr: 'auto',
        pr:4
      }}
    >
      {!me ? `${firstName} ,` : 'You ,' } &nbsp;
      {formatDistanceToNowStrict(new Date(message.date), {
        addSuffix: true,
      })}
    </Typography>
  );


 

  const renderBody = (
    <Stack
      sx={{
        p: 1.5,
        minWidth: 48,
        maxWidth: 320,
        borderRadius: 1,
        typography: 'body2',
        // bgcolor: 'background.neutral',
        color: 'grey.800',
        bgcolor: 'primary.lighter',
        ...(hasImage && {
          p: 0,
          bgcolor: 'transparent',
        }),
        position: 'relative', 
      }}
    >
      {hasImage ? (
        <Box>
          <IconButton
            className="message-actions"
            size="small"
            sx={{
              position: 'absolute',
              top: -28,
              ...(!me && {
                right: 0,
              }),
              ...(me && {
                left: -10,
              }),
            }}
          >
            {children}
          </IconButton>
          <Box
            component="img"
            alt="attachment"
            src={body}
            sx={{
              minHeight: 220,
              borderRadius: 1.5,
              cursor: 'pointer',
              '&:hover': {
                opacity: 0.9,
              },
            }}
            onClick={() => onClick && onClick(message.uuid)}
          />
        </Box>
      ) : (
        <Box>
          <IconButton
            className="message-actions"
            size="small"
            sx={{
              position: 'absolute',
              // opacity: 0,
              top: -28,
              
                right: 0,
              
              transition: (theme) =>
                theme.transitions.create(['opacity'], {
                duration: theme.transitions.duration.shorter,
                
              }),
            }}
          >
            
              {children}
          </IconButton>
          
          <Box onClick={() => onClick && onClick(message.uuid)}>
          {messageUp}
          {messageUpdated &&
                <Typography
                  noWrap
                  variant="caption"
                  sx={{
                    mb: 1,
                    color: 'text.disabled',
                    ml:1
                  }}      
                >
                    (Edited)
                </Typography>
            }
            </Box>
        </Box>
      )}
    </Stack>
  );
  

  
  // const renderReactions = (
  //   // <Stack direction="row" spacing={0} mt={-1} sx={{zIndex:11}}>
  //   //   {reactions.map((emoji, index) => (
  //   //     <Typography key={index} variant="body2" sx={{ fontSize: '0.8rem' }}>
  //   //       {emoji}
  //   //     </Typography>
  //   //   ))}
  //   // </Stack>
    
  //   <Chip avatar={
  //       <>
  //       {reactions.map((emoji, index) => (
  //         <Avatar sx={{background:'transparent'}}>
  //             <Typography key={index} variant="body2" sx={{ fontSize: '0.8rem' }}>
  //               {emoji}
  //             </Typography>
  //             </Avatar>
  //           ))}
  //       </>
  //     } 
  //     sx={{ mt:-2,zIndex:11,background:'grey'}}
  //     size='small'
  //     variant='soft'
  //   />
  // );

  const handleRemoveReaction = (index: number) => {
    setReactions(prevReactions => prevReactions.filter((_, i) => i !== index));
  };
  
  const renderAllreaction = (
    <Stack spacing={0}>
      <>
        {reactions.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={
        <>
        {reactions.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], 2),borderRadius: 2,height:20,mr:'85%'}}
      size='small'
      variant='filled'
      label={<Typography variant="body2" sx={{ fontSize: '0.8rem' ,color:'black'}}>
            {reactions.length}
          </Typography>}
      onClick={handleChipClick}
    />
  );


  return (
    <Stack direction="row" justifyContent={'unset'} alignItems={'flex-start'}>
      {<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,
              },
            },
            cursor:'pointer'
          }}
          // onClick={() => onClick && onClick(message.id)}
        > 
          {renderBody}
          {/* {!update ? renderActions : <></>} */}
        </Stack>
        {reactions.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>
  );
}
