import { useCallback } from 'react';
import { formatDistanceToNowStrict } from 'date-fns';

import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Badge from '@mui/material/Badge';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import AvatarGroup from '@mui/material/AvatarGroup';
import ListItemText from '@mui/material/ListItemText';
import ListItemButton from '@mui/material/ListItemButton';

import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks';

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

import { clickConversation } from '@/shared/api/chat';

import { IChatConversation, IChatConversationClient, IChatMessage } from '@/shared/types/chat';

import { useGetNavItem } from '@/hooks';

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

type Props = {
  selected: boolean;
  collapse: boolean;
  onCloseMobile: VoidFunction;
  conversation: IChatConversationClient;
};

export default function ChatNavItem({ selected, collapse, conversation, onCloseMobile }: Props) {
  const { user1 } = useMockedUser();

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

  const router = useRouter();

  const sortedMessages = [...conversation.messages].sort((a:IChatMessage, b:IChatMessage) => a.id - b.id)

  const { group, displayName, displayText, participants, lastActivity, hasOnlineInGroup,lastMessage} =
    useGetNavItem({
      conversation,
      currentUserId: `${user1?.uuid}`,
      
    });

  const singleParticipant = participants[0];
  
  const { firstname,lastname, avatarUrl, status } = singleParticipant;
  

  const handleClickConversation = useCallback(async () => {
    try {
      if (!mdUp) {
        onCloseMobile();
      }

      await clickConversation(conversation.uuid);

      router.push(`${paths.dashboard.chat}?id=${conversation.uuid}`);
    } catch (error) {
      console.error(error);
    }
  }, [conversation.uuid, mdUp, onCloseMobile, router]);
  
  const renderGroup = (
    <>
      <Stack direction="row" alignItems="center" spacing={2} >
        <Box>
          <Badge
            variant={hasOnlineInGroup ? 'online' : 'invisible'}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
          >
            <AvatarGroup variant="compact" sx={{ width: 48, height: 48 }}>
              {participants.slice(0, 2).map((participant) => (
                <Avatar key={participant.uuid} alt={participant.firstname} src={participant.avatarUrl} />
              ))}
            </AvatarGroup>
          </Badge>
        </Box>
        <Stack direction="column" alignItems="flex-start" sx={{width:1}} spacing={1} >
          <Typography variant='subtitle1'>{conversation.name} </Typography>
          <ListItemText
                sx={{ width:mdUp?150:200 }}
                primary={displayText}
                primaryTypographyProps={{
                  noWrap: true,
                  variant: conversation.unreadCount ? 'subtitle2' : 'body2',
                  color: conversation.unreadCount ? 'text.primary' : 'text.secondary',
                }}
              />
          </Stack>
      </Stack>
      
      
    </>
  ); //CHANGES
  const renderSingle = (
    <Badge key={status} variant={status} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}>
      <Avatar alt={firstname} src={avatarUrl} sx={{ width: 48, height: 48 }} >{firstname[0].toUpperCase()}</Avatar>
    </Badge>
  );

  return (
    <ListItemButton
      disableGutters
      onClick={handleClickConversation}
      sx={{
        py: 1.5,
        px: 2.5,
        ...(selected && {
          bgcolor: 'action.selected',
        }),
      }}
    >
      <Badge
        color="error"
        overlap="circular"
        badgeContent={collapse ? conversation.unreadCount : 0}
      >
        {group ? renderGroup : renderSingle}
      </Badge>

      {!collapse && (
        <>
          {!group && <ListItemText
            sx={{ ml: 2,width:600 }}
            primary={displayName}
            primaryTypographyProps={{
              noWrap: true,
              variant: 'subtitle2',
            }}
            secondary={displayText}
            secondaryTypographyProps={{
              noWrap: true,
              component: 'span',
              variant: conversation.unreadCount ? 'subtitle2' : 'body2',
              color: conversation.unreadCount ? 'text.primary' : 'text.secondary',
            }}
          />}

          <Stack alignItems="flex-end" sx={{ ml:2, height: 44,width:1}}>
            <Typography
              noWrap
              variant="body2"
              component="span"
              sx={{
                mb: 1.5,
                fontSize: 12,
                color: 'text.disabled',
              }}
            >
              {formatDistanceToNowStrict(new Date(sortedMessages[sortedMessages.length -1]?.date), {
                addSuffix: false,
              })}
            </Typography>

            {!!conversation.unreadCount && (
              <Box
                sx={{
                  width: 8,
                  height: 8,
                  bgcolor: 'info.main',
                  borderRadius: '50%',
                }}
              />
            )}
          </Stack>
        </>
      )}
    </ListItemButton>
  );
}
