import { Component, OnInit,OnDestroy } from '@angular/core';
import { NavController } from '@ionic/angular';
import * as Parse from 'parse';
import { interval, Subscription } from 'rxjs';

interface ChatHistoryItem {
  chatId: number; // Adjust chatId to number type
  username: string;
  userChatOrder: number; // Add userChatOrder field
  userChat: string;
  aiChat: string;
}

@Component({
  selector: 'app-ai-chat',
  templateUrl: './ai-chat.page.html',
  styleUrls: ['./ai-chat.page.scss'],
})
export class AiChatPage implements OnInit {
  chatHistory: ChatHistoryItem[] = [];
  private loadChatHistorySubscription: Subscription | undefined;

  constructor(private navCtrl: NavController) {}

  ngOnInit() {
    this.loadChatHistory();
    //每隔一秒检测登录状况
    this.loadChatHistorySubscription = interval(1000).subscribe(() => {
      this.loadChatHistory();
      //console.log(this.username);
    });
  }
  ngOnDestroy() {
    if (this.loadChatHistorySubscription) {
      this.loadChatHistorySubscription.unsubscribe();
    }
  }

  async loadChatHistory() {
    try {
      const Chat = Parse.Object.extend('ai_chat');
      const query = new Parse.Query(Chat);
      query.select('chatId', 'username', 'userChatOrder', 'userChat', 'aiChat');
      query.descending('createdAt'); // Ensure latest chat is fetched first
      const results = await query.find();

      const groupedChats: { [key: number]: ChatHistoryItem } = results.reduce((acc: { [key: number]: ChatHistoryItem }, chat: any) => {
        const chatId = chat.get('chatId');
        if (!acc[chatId]) {
          acc[chatId] = {
            chatId,
            username: chat.get('username'),
            userChatOrder: chat.get('userChatOrder'),
            userChat: chat.get('userChat'),
            aiChat: chat.get('aiChat')
          };
        }
        return acc;
      }, {});

      this.chatHistory = Object.values(groupedChats).map(chat => {
        // Filter to only keep the first message for each chatId
        const firstMessage = results.find(item => item.get('chatId') === chat.chatId && item.get('userChatOrder') === 1);
        return {
          chatId: chat.chatId,
          username: firstMessage?.get('username') || chat.username,
          userChatOrder: firstMessage?.get('userChatOrder') || chat.userChatOrder,
          userChat: firstMessage?.get('userChat') || chat.userChat,
          aiChat: firstMessage?.get('aiChat') || chat.aiChat
        };
      });

    } catch (error) {
      console.error('Error loading chat history:', error);
    }
  }

  goToChat(chatId: number) {
    this.navCtrl.navigateForward(`/tabs/tab2`, {
      queryParams: { chatId: chatId.toString() } // Ensure chatId is passed as string
    });
  }

  async startNewChat() {
    const Chat = Parse.Object.extend('ai_chat');
    const query = new Parse.Query(Chat);
    query.descending('chatId');
    const latestChat = await query.first();
    const newChatId = latestChat ? latestChat.get('chatId') + 1 : 1;

    this.navCtrl.navigateForward(`/tabs/tab2`, {
      queryParams: { chatId: newChatId.toString() } // Ensure chatId is passed as string
    });
  }
}
