'use client';

import React, { useState, useEffect, useRef } from 'react';
import { ChatWindowProps } from '../../types';
import './ChatWindow.css';

// 根据用户名生成随机颜色
const stringToColor = (string: string) => {
  let hash = 0;
  for (let i = 0; i < string.length; i += 1) {
    hash = string.charCodeAt(i) + ((hash << 5) - hash);
  }
  let color = '#';
  for (let i = 0; i < 3; i += 1) {
    const value = (hash >> (i * 8)) & 0xff;
    color += `00${value.toString(16)}`.slice(-2);
  }
  return color;
};

// 格式化时间戳
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 用户头像组件
const UserAvatar = ({ name }: { name: string }) => {
  const bgColor = stringToColor(name);
  const initials = name.charAt(0).toUpperCase();
  
  return (
    <div 
      className="user-avatar"
      style={{ backgroundColor: bgColor }}
    >
      {initials}
    </div>
  );
};

const ChatWindow = ({
  roomName,
  messages,
  onSendNewMessage,
}: ChatWindowProps) => {
  const [newMessage, setNewMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);
  
  const handleSendMessage = () => {
    if (!newMessage.trim()) return;
    
    onSendNewMessage(newMessage.trim());
    setNewMessage('');
  };
  
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };
  
  return (
    <div className="chat-window">
      {/* 顶部标题栏 */}
      <div className="chat-header">
        <div className="room-name">{roomName}</div>
        <div className="message-count">({messages.length}条消息)</div>
      </div>
      
      {/* 消息区域 */}
      <div className="messages-container">
        <div className="messages-list">
          {messages.map((message) => (
            <div key={message.messageId} className="message-row">
              <div className="avatar-container">
                <UserAvatar name={message.sender} />
              </div>
              
              <div className="message-content-wrapper">
                <div className="sender-name">{message.sender}</div>
                
                <div className="bubble-time-container">
                  <div className="message-bubble">
                    {message.content}
                  </div>
                  <div className="message-time">
                    {formatTime(message.time)}
                  </div>
                </div>
              </div>
            </div>
          ))}
          <div ref={messagesEndRef} />
        </div>
      </div>
      
      {/* 输入区域 */}
      <div className="input-container">
        <div className="input-wrapper">
          <textarea
            className="message-input"
            placeholder="输入消息..."
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            onKeyDown={handleKeyPress}
          />
          <button
            className={`send-button ${
              newMessage ? 'send-button-active' : 'send-button-disabled'
            }`}
            onClick={handleSendMessage}
            disabled={!newMessage}
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
};

export default ChatWindow;