// components/RoomList/RoomList.tsx
'use client';

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

const getRandomColor = (seed: number) => {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', 
    '#98D8C8', '#F78FB3', '#7BED9F', '#FFD166'
  ];
  return colors[seed % colors.length];
};

const getInitials = (name: string) => {
  const safeName = name || '';
  return safeName
    .split(' ')
    .map(part => part.charAt(0).toUpperCase())
    .join('')
    .slice(0, 2);
};

const formatTimeAgo = (timestamp: number | undefined): string => {
  if (!timestamp) return "";
  
  const now = new Date();
  const messageTime = new Date(timestamp);
  const diffInSeconds = Math.floor((now.getTime() - messageTime.getTime()) / 1000);
  
  // 规则定义
  if (diffInSeconds < 60) {
    return "刚刚";
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  }
  
  const diffInDays = Math.floor(diffInHours / 24);
  if (diffInDays === 1) {
    return "昨天";
  }
  if (diffInDays < 7) {
    return `${diffInDays}天前`;
  }
  
  // 超过一周显示具体日期
  return messageTime.toLocaleDateString('zh-CN', {
    month: 'numeric',
    day: 'numeric'
  });
};

const RoomList: React.FC<RoomListProps> = ({ 
  rooms, 
  onSelect, 
  selectedRoomId,
  onAddRoom,
  onDeleteRoom
}) => {
  const [slidingRoomId, setSlidingRoomId] = useState<number | null>(null);
  const [showAddRoomInput, setShowAddRoomInput] = useState(false);
  const [newRoomName, setNewRoomName] = useState('');
  const [error, setError] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  // 自动聚焦输入框
  useEffect(() => {
    if (showAddRoomInput && inputRef.current) {
      inputRef.current.focus();
    }
  }, [showAddRoomInput]);

  const toggleSlide = (roomId: number, e: React.MouseEvent) => {
    e.stopPropagation();
    setSlidingRoomId(slidingRoomId === roomId ? null : roomId);
  };

  const handleSelect = (roomId: number) => {
    setSlidingRoomId(null);
    onSelect(roomId);
  };

  const handleAddRoom = () => {
    setShowAddRoomInput(true);
    setNewRoomName('');
    setError('');
  };

  const handleCreateRoom = async () => {
    // 修复: 正确使用 trim() 方法（不带参数）
    const trimmedName = newRoomName.trim();
    
    if (!trimmedName) {
      setError('房间名不能为空');
      return;
    }
    
    try {
      await onAddRoom(trimmedName);
      setShowAddRoomInput(false);
      setNewRoomName('');
      setError('');
    } catch (err) {
      setError('创建房间失败，请重试:');
      console.log(err)
    }
  };

  const handleCancelAddRoom = () => {
    setShowAddRoomInput(false);
    setNewRoomName('');
    setError('');
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleCreateRoom();
    } else if (e.key === 'Escape') {
      handleCancelAddRoom();
    }
  };

  return (
    <div className="room-list-container">
      <div className="room-list-header">
        <h2>聊天室</h2>
        <button 
          className="add-room-button"
          onClick={handleAddRoom}
          aria-label="添加聊天室"
          disabled={showAddRoomInput}
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px">
            <path d="M0 0h24v24H0z" fill="none"/>
            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
          </svg>
        </button>
      </div>
      
      {/* 添加房间输入框 */}
      {showAddRoomInput && (
        <div className="add-room-input-container">
          <input
            ref={inputRef}
            type="text"
            value={newRoomName}
            onChange={(e) => setNewRoomName(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="输入房间名称"
            className="add-room-input"
          />
          <div className="add-room-buttons">
            <button 
              className="cancel-add-button"
              onClick={handleCancelAddRoom}
              aria-label="取消"
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#868e96" width="20px" height="20px">
                <path d="M0 0h24v24H0z" fill="none"/>
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
            </button>
            <button 
              className="confirm-add-button"
              onClick={handleCreateRoom}
              aria-label="创建房间"
            >
              创建
            </button>
          </div>
          {error && <div className="add-room-error">{error}</div>}
        </div>
      )}
      
      <div className="room-list-scrollable">
        {rooms.map(room => (
          <div 
            key={room.roomId}
            className={`room-item-container ${selectedRoomId === room.roomId ? 'selected' : ''}`}
            onClick={() => handleSelect(room.roomId)}
          >
            <div 
              className={`room-item ${slidingRoomId === room.roomId ? 'sliding' : ''}`}
            >
              <div 
                className="room-avatar"
                style={{ backgroundColor: getRandomColor(room.roomId) }}
              >
                {getInitials(room.roomName)}
              </div>
              
              <div className="room-info">
                <div className="room-header">
                  <p className="room-name">{room.roomName}</p>
                  <span className="room-time">{formatTimeAgo(room.lastMessage?.time)}</span>
                </div>
                <p className="room-preview">{room.lastMessage?.content}</p>
              </div>

              {/* 右下角灰色"<"按钮 */}
              <button 
                className="slide-button"
                onClick={(e) => toggleSlide(room.roomId, e)}
                aria-label="滑动选项"
              >
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#868e96" width="16px" height="16px">
                  <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
                </svg>
              </button>
            </div>
            
            {/* 苹果风格的删除按钮 */}
            <div className="delete-container">
              <button 
                className="delete-button"
                onClick={(e) => {
                  e.stopPropagation();
                  onDeleteRoom(room.roomId);
                }}
                aria-label="删除聊天室"
              >
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="20px" height="20px">
                  <path d="M0 0h24v24H0z" fill="none"/>
                  <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                </svg>
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default RoomList;