/**
 * Lego 03 / Lego 14 — n8n RAG Chatbot Tab (Intelligence)
 *
 * Chat messages are sent to NestJS via Socket.io (chat:send).
 * NestJS proxies them server-to-server to n8n — no CORS constraint.
 * The n8n webhook URL lives in NestJS .env (N8N_WEBHOOK_URL).
 */

import {
  Component,
  signal,
  ViewChild,
  ElementRef,
  AfterViewChecked,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { SurveillanceService } from '../../services/surveillance.service';
import { ChatSocketService } from '../../services/chat-socket.service';

export interface ChatMessage {
  role: 'user' | 'bot' | 'error';
  text: string;
  timestamp: Date;
  durationMs?: number;
}

@Component({
  selector: 'app-chatbot',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './chatbot.component.html',
  styleUrls: ['./chatbot.component.scss'],
})
export class ChatbotComponent implements AfterViewChecked {
  @ViewChild('messageList') messageListRef!: ElementRef<HTMLDivElement>;

  messages = signal<ChatMessage[]>([
    {
      role: 'bot',
      text: 'RAG pipeline ready. Ask me about palm oil operational data.',
      timestamp: new Date(),
    },
  ]);

  inputText = '';
  loading = signal<boolean>(false);

  private shouldScrollToBottom = false;

  constructor(
    public chatSocket: ChatSocketService,
    public surveillance: SurveillanceService,
  ) {}

  ngAfterViewChecked(): void {
    if (this.shouldScrollToBottom) {
      this.scrollToBottom();
      this.shouldScrollToBottom = false;
    }
  }

  async sendMessage(): Promise<void> {
    const text = this.inputText.trim();
    if (!text || this.loading() || this.chatSocket.sending()) return;

    // Push user message immediately
    this.pushMessage({ role: 'user', text, timestamp: new Date() });
    this.inputText = '';
    this.loading.set(true);

    const start = Date.now();

    try {
      const response = await this.chatSocket.send(text);
      const durationMs = Date.now() - start;

      // n8n may return { output }, { answer }, { response }, { text }, or a raw string
      const botText =
        response?.output ??
        response?.answer ??
        response?.response ??
        response?.text ??
        (typeof response === 'string' ? response : JSON.stringify(response));

      this.pushMessage({ role: 'bot', text: botText, timestamp: new Date(), durationMs });
    } catch (err: any) {
      this.pushMessage({
        role: 'error',
        text: `Proxy error: ${err.message ?? 'Unknown error'}. Check NestJS → n8n connection.`,
        timestamp: new Date(),
      });
    } finally {
      this.loading.set(false);
    }
  }

  onEnter(event: KeyboardEvent): void {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      this.sendMessage();
    }
  }

  onClearChat(): void {
    this.messages.set([
      {
        role: 'bot',
        text: 'Chat cleared. RAG pipeline ready.',
        timestamp: new Date(),
      },
    ]);
    this.chatSocket.clearBackendSession();
  }

  private pushMessage(msg: ChatMessage): void {
    this.messages.update(msgs => [...msgs, msg]);
    this.shouldScrollToBottom = true;
  }

  private scrollToBottom(): void {
    try {
      const el = this.messageListRef?.nativeElement;
      if (el) el.scrollTop = el.scrollHeight;
    } catch {}
  }

  formatTime(date: Date): string {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  }
}
