// page.tsx
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';

// 服务导入
import { getFetcher, postFetcher} from'@/api/apiService';
import { API_ENDPOINTS } from '@/api/apiEndpoints';
import {Message, RoomListRes, UpdateMessageRes, RoomPreviewInfo} from '@/types/index';

// 组件导入
import RoomList from '@/components/RoomList/RoomList';
import ChatWindow from '@/components/ChatWindow/ChatWindow';

// 本地样式
import './chatroom.css';

const Chatroom = () => {
  const searchParams = useSearchParams();
  const username = searchParams.get('username') || '匿名用户';

  // 定义状态
  const [selectedRoom, setSelectedRoom] = useState<RoomPreviewInfo | null>(null);
  const [selectedMessages, setSelectedMessages] = useState<Message[]>([]);
  
  // 获取房间列表 - 使用SWR
  const { 
    data: roomListRes,
    mutate: mutateRoomList
  } = useSWR<RoomListRes>(API_ENDPOINTS.ROOMS.LIST, getFetcher, {
    refreshInterval: 3000,
    revalidateOnFocus: true,
  });

  // 更新消息的方式
  const {
    data: updateMessageRes,
    mutate: mutateUpdateMessage
  } = useSWR<UpdateMessageRes>({
    url: API_ENDPOINTS.MESSAGES.UPDATE,
    arg: {
      roomId: selectedRoom?.roomId,
      sinceMessageId: selectedMessages.at(-1)?.messageId || 0
    }
  }, getFetcher, {
    refreshInterval: 1000,
    revalidateOnFocus: true,
  });

    // 获取初始消息的函数
  const getInitMessage = useCallback(async (roomId: number): Promise<Message[]> => {
    try {
      const roomMessageListRes = await getFetcher(
        API_ENDPOINTS.MESSAGES.LIST,
        { arg: { roomId } }
      );
      return roomMessageListRes?.messages || [];
    } catch (error) {
      console.error("Failed to fetch init message:", error);
      return [];
    }
  }, []);


  useEffect(() => {
    if (updateMessageRes?.messages?.length && selectedRoom) {
      setSelectedMessages(prev => {
        // 过滤掉可能重复的消息（基于消息ID）
        const newMessages = updateMessageRes.messages.filter(
          msg => !prev.some(m => m.messageId === msg.messageId)
        );
        
        return [...prev, ...newMessages];
      });
    }
  }, [updateMessageRes, selectedRoom]);

  // 当房间列表更新时设置默认选中房间
  useEffect(() => {
    // 使用可选链 + 空值合并运算符提供默认值
    const hasRooms = (roomListRes?.rooms?.length ?? 0) > 0;
    
    if (hasRooms && !selectedRoom) {
      // 安全访问第一个房间
      const firstRoom = roomListRes?.rooms?.[0];
      if (firstRoom) {
        setSelectedRoom(firstRoom);
      }
    }
  }, [roomListRes, selectedRoom]);

  // 获取选中房间的消息
  useEffect(() => {
    if (!selectedRoom) return;
    
    const fetchMessages = async () => {
      try {
        const messages = await getInitMessage(selectedRoom.roomId);
        setSelectedMessages(messages || []);
      } catch (error) {
        console.error("Failed to fetch new message:", error);
        setSelectedMessages([]);
      }
    };

    fetchMessages();
  }, [selectedRoom, getInitMessage]);

  // 添加房间并自动选中新房间
  const handleAddRoom = async (roomName: string): Promise<number> => {
    try {
      const newRoomIdInfo = await postFetcher(API_ENDPOINTS.ROOMS.ADD, {
        arg: {
          user: username,
          roomName: roomName
        }
      });

      // 重新验证房间列表
      const updatedRoomList = await mutateRoomList();

      // 在新房间列表中找到并选中新创建的房间
      if (updatedRoomList) {
        const newRoom = updatedRoomList.rooms.find(room => room.roomId === newRoomIdInfo.roomId);
        if (newRoom) {
          setSelectedRoom(newRoom);
        }
      }
      
      return newRoomIdInfo.roomId;
    } catch (error) {
      console.error("Failed to add room:", error);
      throw error;
    }
  }

  // 删除房间并检查当前选中状态
  const handleDeleteRoom = async (id: number) => {
    try {
      await postFetcher(API_ENDPOINTS.ROOMS.DELETE, {
        arg: {
          user: username,
          roomId: id
        }
      });
      
      // 重新验证房间列表
      const updatedRoomList = await mutateRoomList();
      
      // 检查当前选中的房间是否被删除
      if (selectedRoom?.roomId === id) {
        // 选择第一个可用房间
        if (updatedRoomList?.rooms && updatedRoomList.rooms.length > 0) {
          setSelectedRoom(updatedRoomList.rooms[0]);
        } else {
          setSelectedRoom(null);
        }
      }
    } catch (error) {
      console.error("Failed to delete room:",error);
      throw error;
    }
  }

  const handleSelectRoom = (roomId: number) => {
    const room = roomListRes?.rooms.find(room => room.roomId === roomId);
    if (room) {
      setSelectedRoom(room);
    } else {
      console.error("setSelectedRoom() found no room");
    }
  }

  const handleSendNewMessage = (newMessage: string) => {
    try {
      postFetcher(API_ENDPOINTS.MESSAGES.ADD, {
        arg: {
          roomId: selectedRoom?.roomId,
          content: newMessage,
          sender: username
        }
      })
      mutateRoomList
      mutateUpdateMessage
    } catch(error) {
      console.error("Failed to send new message:", error);
    }
  }

  return (
    <div className='chatroom-page'>
      <div className="roomList-container">
        <RoomList 
          rooms={roomListRes?.rooms||[]} 
          selectedRoomId={selectedRoom?.roomId||null}
          onSelect={handleSelectRoom} 
          onAddRoom={handleAddRoom}
          onDeleteRoom={handleDeleteRoom}
        />
      </div>
      <div className='chatwindow-container'>
        {selectedRoom ? (
          <ChatWindow 
            roomName={selectedRoom?.roomName||''}
            messages={selectedMessages||[]}
            onSendNewMessage={handleSendNewMessage}
          />
        ) : (
          <div className="no-room-selected">
            <p>{'>'} 请选择一个房间开始聊天</p>
            {roomListRes?.rooms?.length === 0 && (
              <p>{'>'} 没有可用房间，请创建一个新房间...</p>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default Chatroom;