'use client';
import { useMemo } from 'react';
import AIRelationTag from '@/components/features/AIRelationTag';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { cn, durationText, getConversationTime } from '@/lib/utils';
import { CustomMessageType } from '@/types/im';
import Image from 'next/image';
import { useRouter } from 'next/navigation';

// 高亮搜索关键词的组件
const HighlightText = ({ text, keyword }: { text: string; keyword?: string }) => {
  if (!keyword || !text) return <span>{text}</span>;

  const parts = text.split(new RegExp(`(${keyword})`, 'gi'));
  return (
    <span>
      {parts.map((part, index) =>
        part.toLowerCase() === keyword.toLowerCase() ? (
          <span key={index} className="text-primary-variant-normal">
            {part}
          </span>
        ) : (
          <span key={index}>{part}</span>
        )
      )}
    </span>
  );
};

// 聊天项组件
export default function ChatSidebarItem({
  conversation,
  isExpanded,
  isSelected = false,
  searchKeyword,
}: {
  isExpanded: boolean;
  isSelected?: boolean;
  searchKeyword?: string;
}) {
  const { avatar, name, lastMessage, unreadCount, updateTime, serverExtension } = conversation;
  const { text, attachment } = lastMessage || {};
  const router = useRouter();

  const { heartbeatVal, heartbeatLevel, isShow } = JSON.parse(serverExtension || '{}') || {};

  const handleChat = () => {
    router.push('/');
  };

  const renderText = () => {
    const { raw } = attachment || {};
    const customData = JSON.parse(raw || '{}');
    const { type, duration } = customData || {};
    if (type === CustomMessageType.CALL_CANCEL) {
      return 'Call Canceled';
    } else if (type === CustomMessageType.CALL) {
      return `Call duration ${durationText(duration)}`;
    } else if (type == CustomMessageType.IMAGE) {
      return '[Image]';
    }
    return text;
  };

  return (
    <div
      className={cn(
        'hover:bg-surface-element-hover flex cursor-pointer items-center gap-2 rounded-full p-1 transition-colors',
        isSelected && 'bg-surface-element-normal'
      )}
      onClick={handleChat}
    >
      {/* 头像 */}
      <div className="relative flex-shrink-0">
        <div className="h-10 w-10 overflow-hidden rounded-full">
          <Avatar className="h-10 w-10">
            <AvatarImage src={avatar || ''} alt={name || ''} className="object-cover" />
            <AvatarFallback>{name?.charAt(0)}</AvatarFallback>
          </Avatar>
        </div>
        {/* 选中状态指示器 */}
        {!!isSelected && (
          <div className="border-primary-variant-normal absolute inset-0 rounded-full border-1 border-solid" />
        )}
        {/* 未读消息数量 */}
        {!!unreadCount && unreadCount > 0 && (
          <Badge count={unreadCount} className="absolute top-[-4px] right-[-4px]" />
        )}
      </div>

      {isExpanded && (
        <div className="min-w-0 flex-1 pr-2">
          <div className="flex items-center justify-between gap-2">
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-1">
                <div className="txt-label-m truncate">
                  <HighlightText text={name || ''} keyword={searchKeyword} />
                </div>
                <div className="flex-shrink-0">
                  {heartbeatLevel && isShow && (
                    <AIRelationTag heartbeatLevel={heartbeatLevel} size="mini" />
                  )}
                </div>
              </div>
              <div className="txt-body-s text-txt-secondary-normal truncate">{renderText()}</div>
            </div>

            <div className="flex-shrink-0">
              <div className="txt-numMonotype-xs text-txt-secondary-normal text-right">
                {getConversationTime(lastMessage?.messageRefer.createTime || updateTime)}
              </div>
              {!!heartbeatVal && heartbeatLevel && (
                <div className="flex items-center justify-end gap-1">
                  <Image src="/icons/heart.svg" alt="heart" width={12} height={12} />
                  <div className="txt-numMonotype-xs text-txt-primary-normal">{heartbeatVal}℃</div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
