import { useEffect, useRef } from 'react';
import { MessageBubble } from './MessageBubble';
import type { Message } from '@/types/chat';

interface MessageListProps {
  messages: Message[];
  hasMoreMessages?: boolean;
  isLoadingHistory?: boolean;
  onLoadMore?: () => void;
}

export function MessageList({
  messages,
  hasMoreMessages = false,
  isLoadingHistory = false,
  onLoadMore,
}: MessageListProps) {
  const bottomRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部（仅在消息追加时，不在加载历史时）
  useEffect(() => {
    if (!isLoadingHistory) {
      bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, isLoadingHistory]);

  if (messages.length === 0 && !isLoadingHistory) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center text-gray-400 p-8">
        <p className="text-sm text-gray-400 dark:text-gray-500">
          开始一段新对话吧
        </p>
      </div>
    );
  }

  return (
    <div
      ref={containerRef}
      className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-pink-200 dark:scrollbar-thumb-pink-900"
    >
      {/* 加载更多历史消息按钮 */}
      {hasMoreMessages && (
        <div className="flex justify-center py-3">
          <button
            onClick={onLoadMore}
            disabled={isLoadingHistory}
            className="text-xs text-gray-400 hover:text-pink-500 disabled:text-gray-300 disabled:cursor-not-allowed px-4 py-1.5 rounded-full bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:border-pink-200 dark:hover:border-pink-800 transition-all"
          >
            {isLoadingHistory ? (
              <span className="flex items-center gap-1.5">
                <svg className="animate-spin h-3 w-3" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                加载中...
              </span>
            ) : (
              '加载更早的消息'
            )}
          </button>
        </div>
      )}

      {messages.map((msg) => (
        <MessageBubble
          key={msg.id}
          id={msg.id}
          role={msg.role}
          content={msg.content}
          timestamp={msg.timestamp}
          isStreaming={msg.isStreaming}
          attachments={msg.attachments}
          msgType={msg.msgType}
          metadata={msg.metadata}
          audioUrl={msg.audioUrl}
        />
      ))}
      <div ref={bottomRef} />
    </div>
  );
}
