import { type FC, useState } from 'react';

import List from '@material-hu/mui/List';
import ListItemButton from '@material-hu/mui/ListItemButton';

import { useScrollToMessageConversation } from 'src/pages/dashboard/Conversations/contexts/ScrollToMessageConversationContext';
import { type ConversationMessage } from 'src/pages/dashboard/Conversations/types';

import Message from './Message';
import PinnedActions from './PinnedActions';

type PinnedMessagesProps = {
  pinnedMessages: ConversationMessage[];
};

const PinnedMessages: FC<PinnedMessagesProps> = ({ pinnedMessages }) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const { scrollToMessage } = useScrollToMessageConversation();

  const safeIndex = Math.min(selectedIndex, pinnedMessages.length - 1);

  const handleSelect = () => {
    const nextIndex = (selectedIndex + 1) % pinnedMessages.length;
    setSelectedIndex(nextIndex);
    scrollToMessage(pinnedMessages[nextIndex].hu_data.message_ts);
  };

  return (
    <List disablePadding>
      <ListItemButton
        onClick={handleSelect}
        sx={{ gap: 1, pr: 3, pl: pinnedMessages.length > 1 ? 2 : 3, py: 1 }}
      >
        <Message
          pinnedMessages={pinnedMessages}
          selectedIndex={safeIndex}
        />
        <PinnedActions
          pinnedMessages={pinnedMessages}
          selectedIndex={safeIndex}
          onSelectIndex={setSelectedIndex}
        />
      </ListItemButton>
    </List>
  );
};

export default PinnedMessages;
