/**
 * ChatView Component
 *
 * 显示聊天消息和输入框
 */

import blessed from 'blessed';
import type { Widgets } from 'blessed';
import type { ChatMessage } from '../types.js';

export interface ChatViewOptions {
  parent: Widgets.Screen;
  left: number | string;
  top: number | string;
  width: number | string;
  height: number | string;
}

export class ChatView {
  private container: Widgets.BoxElement;
  private messageList: Widgets.BoxElement;
  private inputBox: Widgets.TextboxElement;
  private messages: ChatMessage[] = [];
  private streamingContent = '';
  private onSend?: (content: string) => void;

  constructor(options: ChatViewOptions) {
    // 主容器
    this.container = blessed.box({
      parent: options.parent,
      left: options.left,
      top: options.top,
      width: options.width,
      height: options.height,
      border: { type: 'line' },
      label: ' Chat ',
      style: {
        border: { fg: 'cyan' },
        label: { fg: 'cyan', bold: true },
      },
    });

    // 消息列表区域
    this.messageList = blessed.box({
      parent: this.container,
      top: 0,
      left: 0,
      right: 0,
      bottom: 3,
      scrollable: true,
      alwaysScroll: true,
      scrollbar: {
        ch: '│',
        style: { fg: 'cyan' },
      },
      mouse: true,
      keys: true,
      vi: true,
      tags: true,
      style: {
        fg: 'white',
      },
    });

    // 输入框
    this.inputBox = blessed.textbox({
      parent: this.container,
      bottom: 0,
      left: 0,
      right: 0,
      height: 3,
      border: { type: 'line' },
      label: ' Message (Enter to send, Esc to cancel) ',
      style: {
        border: { fg: 'green' },
        label: { fg: 'green' },
        focus: {
          border: { fg: 'yellow' },
        },
      },
      inputOnFocus: true,
    });

    this.setupKeyBindings();
  }

  private setupKeyBindings(): void {
    // 输入框提交
    this.inputBox.on('submit', (value) => {
      const content = value.trim();
      if (content && this.onSend) {
        this.onSend(content);
      }
      this.inputBox.clearValue();
      this.inputBox.focus();
      this.render();
    });

    // 取消输入
    this.inputBox.on('cancel', () => {
      this.inputBox.clearValue();
      this.render();
    });
  }

  /**
   * 设置消息发送回调
   */
  setOnSend(callback: (content: string) => void): void {
    this.onSend = callback;
  }

  /**
   * 添加消息
   */
  addMessage(message: ChatMessage): void {
    this.messages.push(message);
    this.updateMessageList();
  }

  /**
   * 设置所有消息
   */
  setMessages(messages: ChatMessage[]): void {
    this.messages = messages;
    this.updateMessageList();
  }

  /**
   * 更新流式内容
   */
  appendStreamingContent(content: string): void {
    this.streamingContent += content;
    this.updateMessageList();
  }

  /**
   * 完成流式输出
   */
  finishStreaming(finalMessage: ChatMessage): void {
    this.streamingContent = '';
    // 替换或添加最终消息
    const lastMsg = this.messages[this.messages.length - 1];
    if (lastMsg && lastMsg.isStreaming) {
      this.messages[this.messages.length - 1] = finalMessage;
    } else {
      this.messages.push(finalMessage);
    }
    this.updateMessageList();
  }

  /**
   * 清空消息
   */
  clearMessages(): void {
    this.messages = [];
    this.streamingContent = '';
    this.updateMessageList();
  }

  /**
   * 更新消息列表显示
   */
  private updateMessageList(): void {
    const lines: string[] = [];

    for (const msg of this.messages) {
      const prefix = msg.role === 'user'
        ? '{blue-fg}{bold}You:{/bold}{/blue-fg} '
        : '{green-fg}{bold}AI:{/bold}{/green-fg} ';

      // 处理多行消息
      const contentLines = msg.content.split('\n');
      contentLines.forEach((line, i) => {
        if (i === 0) {
          lines.push(prefix + line);
        } else {
          lines.push('    ' + line);
        }
      });
      lines.push('');
    }

    // 添加流式内容
    if (this.streamingContent) {
      const streamLines = this.streamingContent.split('\n');
      streamLines.forEach((line, i) => {
        if (i === 0) {
          lines.push('{green-fg}{bold}AI:{/bold}{/green-fg} ' + line);
        } else {
          lines.push('    ' + line);
        }
      });
      lines.push('{yellow-fg}▌{/yellow-fg}'); // 光标指示
    }

    this.messageList.setContent(lines.join('\n'));
    this.scrollToBottom();
    this.render();
  }

  /**
   * 滚动到底部
   */
  private scrollToBottom(): void {
    this.messageList.setScrollPerc(100);
  }

  /**
   * 聚焦输入框
   */
  focus(): void {
    this.inputBox.focus();
  }

  /**
   * 渲染
   */
  render(): void {
    this.container.screen.render();
  }

  /**
   * 销毁
   */
  destroy(): void {
    this.container.destroy();
  }

  /**
   * 获取容器元素
   */
  getElement(): Widgets.BoxElement {
    return this.container;
  }
}
