import React from 'react';
import { DeleteIcon } from '../../assets/icons';
import { Conversation } from '../../contexts/ChatContext';
import useRenderTracker from '../../hooks/useRenderTracker';

interface ConversationGroupProps {
  category: string;
  conversations: Conversation[];
  currentConversationId: string | null;
  onSelectConversation: (id: string) => void;
  onDeleteConversation: (conversationName: string, conversationId: string) => void;
  className?: string;
}

const ConversationGroup: React.FC<ConversationGroupProps> = ({
  category,
  conversations,
  currentConversationId,
  onSelectConversation,
  onDeleteConversation,
  className,
}) => {

  useRenderTracker('ConversationGroup', {
    category,
    conversations,
    currentConversationId,
    onSelectConversation,
    onDeleteConversation,
  });

  return (
    <div className={className}>  
      <div className="sticky top-0 text-xs font-semibold p-2 bg-background-light dark:bg-background-dark bg-gradient-to-r from-background-light to-gray-300/10 dark:from-background-dark dark:to-gray-600/5 z-10">
        {category}
      </div>
      {conversations
        .sort((a, b) => b.updated_at - a.updated_at)
        .map((conv) => (
          <div
            key={conv.conversation_id}
            className={`group relative flex min-w-0 items-center text-[.9rem] text-gray-600 dark:text-gray-300 hover:bg-secondary/10 dark:hover:bg-secondary/40 rounded-md p-2 mb-1 cursor-pointer duration-0 ${
              conv.conversation_id === currentConversationId
                ? 'bg-secondary/10 dark:bg-secondary/40 text-secondary-foreground'
                : ''
            }`}
            onClick={() => onSelectConversation(conv.conversation_id)}
          >
            <div className="min-w-0 w-full group-hover:w-[calc(100%-24px)] overflow-hidden whitespace-nowrap transition-all duration-0">
              {conv.title || 'New Chat'}
            </div>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onDeleteConversation(conv.title, conv.conversation_id);
              }}
              className="absolute right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-0"
              aria-label="Delete conversation"
            >
              <DeleteIcon className="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
            </button>
          </div>
        ))}
    </div>
  );
};

export default React.memo(ConversationGroup);
