import { Component, ElementRef, ViewChild, AfterViewChecked } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import Parse from 'parse'; // ⚠️ 确保 tsconfig.json 启用了 allowSyntheticDefaultImports

import { TestChatCompletion, TestChatMessage } from './TestChatCompletion';

interface ChatMessage {
  from: 'user' | 'ai';
  text: string;
}

@Component({
  selector: 'app-ai-chat',
  templateUrl: './ai-chat.component.html',
  styleUrls: ['./ai-chat.component.scss'],
  standalone: true,
  imports: [FormsModule, CommonModule],
})
export class AiChatComponent implements AfterViewChecked {
  @ViewChild('chatMessages') private chatMessagesContainer!: ElementRef;

  inputMessage = '';
  isLoading = false;
  chats: ChatMessage[] = [
    { from: 'ai', text: '您好！有什么可以帮您？' }
  ];
  suggestions = [
    '如何绑定 Steam 账号？',
    '忘记密码怎么办？',
    '如何进行身份验证？'
  ];
  chatHistory: any[] = [];

  constructor(private router: Router) {}

  ngAfterViewChecked() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    try {
      const el = this.chatMessagesContainer.nativeElement;
      el.scrollTop = el.scrollHeight;
    } catch (err) {}
  }

  goBack() {
    this.router.navigate(['/tabs/tab5']);
  }

  async sendMessage() {
    const msg = this.inputMessage.trim();
    if (!msg) return;

    this.chats.push({ from: 'user', text: msg });
    this.inputMessage = '';
    this.isLoading = true;

    const messages: TestChatMessage[] = this.chats.map(c => ({
      role: c.from === 'user' ? 'user' : 'assistant',
      content: c.text
    }));

    const chatCompletion = new TestChatCompletion(messages);
    let aiReply = '';

    try {
      await chatCompletion.createCompletionByStream((delta: string) => {
        aiReply += delta;
        if (this.chats.length > 0 && this.chats[this.chats.length - 1].from === 'ai') {
          this.chats[this.chats.length - 1].text = aiReply;
        } else {
          this.chats.push({ from: 'ai', text: aiReply });
        }
      });
    } catch (err) {
      console.error('调用 AI 失败', err);
      this.chats.push({ from: 'ai', text: '⚠️ 抱歉，AI 回复失败，请稍后再试。' });
    } finally {
      this.isLoading = false;
      await this.saveChatRecord();
    }
  }

  onSuggestionClick(suggestion: string) {
    this.inputMessage = suggestion;
  }

  async saveChatRecord() {
    const user = Parse.User.current();
    const chatId = 'chat_' + Date.now();

    const TrainingConsult = Parse.Object.extend('TrainingConsult');
    const query = new Parse.Query(TrainingConsult);
    query.equalTo('chatId', chatId);

    try {
      const existingRecord = await query.first();
      const record = existingRecord ?? new TrainingConsult();

      record.set('user', user);
      record.set('chatId', chatId);
      record.set('messageList', this.chats.map(c => ({
        role: c.from === 'user' ? 'user' : 'assistant',
        content: c.text
      })));

      await record.save();
      console.log('✅ 聊天记录已保存:', record);
    } catch (err) {
      console.error('❌ 保存聊天记录失败:', err);
    }
  }

  async loadChatHistory() {
    const query = new Parse.Query('TrainingConsult');
    query.equalTo('user', Parse.User.current());
    query.descending('updatedAt');
    query.limit(10);

    try {
      this.chatHistory = await query.find();
    } catch (err) {
      console.error('❌ 获取聊天记录失败:', err);
    }
  }

  restoreChat(chat: any) {
    const messageList = chat.get('messageList') || [];
    this.chats = messageList.map((m: any) => ({
      from: m.role === 'user' ? 'user' : 'ai',
      text: m.content
    }));
    this.scrollToBottom();
  }
}
