/**
 * SessionList Component
 *
 * 显示会话列表
 */

import blessed from 'blessed';
import type { Widgets } from 'blessed';
import type { Session } from '../../client/api.js';

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

export class SessionList {
  private container: Widgets.BoxElement;
  private list: Widgets.ListElement;
  private sessions: Session[] = [];
  private onSelect?: (session: Session) => void;
  private onCreate?: () => void;
  private onDelete?: (session: Session) => void;

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

    // 会话列表
    this.list = blessed.list({
      parent: this.container,
      top: 0,
      left: 0,
      right: 0,
      bottom: 2,
      keys: true,
      vi: true,
      mouse: true,
      style: {
        selected: {
          bg: 'blue',
          fg: 'white',
          bold: true,
        },
        item: {
          fg: 'white',
        },
      },
      scrollbar: {
        ch: '│',
        style: { fg: 'cyan' },
      },
    });

    // 底部提示
    blessed.box({
      parent: this.container,
      bottom: 0,
      left: 0,
      right: 0,
      height: 1,
      content: '{gray-fg}n: New  d: Delete  Enter: Select{/gray-fg}',
      tags: true,
      style: {
        fg: 'gray',
      },
    });

    this.setupKeyBindings();
  }

  private setupKeyBindings(): void {
    // 选择会话
    this.list.on('select', (_item, index) => {
      if (index === 0 && this.onCreate) {
        // 第一项是 "New Session"
        this.onCreate();
      } else if (this.sessions[index - 1] && this.onSelect) {
        this.onSelect(this.sessions[index - 1]);
      }
    });

    // 快捷键: n 创建新会话
    this.list.key('n', () => {
      if (this.onCreate) {
        this.onCreate();
      }
    });

    // 快捷键: d 删除会话
    this.list.key('d', () => {
      const selectedIndex = (this.list as any).selected;
      if (selectedIndex > 0 && this.sessions[selectedIndex - 1] && this.onDelete) {
        this.onDelete(this.sessions[selectedIndex - 1]);
      }
    });
  }

  /**
   * 设置会话选择回调
   */
  setOnSelect(callback: (session: Session) => void): void {
    this.onSelect = callback;
  }

  /**
   * 设置创建会话回调
   */
  setOnCreate(callback: () => void): void {
    this.onCreate = callback;
  }

  /**
   * 设置删除会话回调
   */
  setOnDelete(callback: (session: Session) => void): void {
    this.onDelete = callback;
  }

  /**
   * 设置会话列表
   */
  setSessions(sessions: Session[]): void {
    this.sessions = sessions;
    this.updateList();
  }

  /**
   * 更新列表显示
   */
  private updateList(): void {
    const items = [
      '{green-fg}+ New Session{/green-fg}',
      ...this.sessions.map((s) => {
        const name = s.name || s.id.slice(0, 8);
        const count = s.messageCount || 0;
        return `${name} (${count} msgs)`;
      }),
    ];

    this.list.setItems(items);
    this.render();
  }

  /**
   * 高亮指定会话
   */
  selectSession(sessionId: string): void {
    const index = this.sessions.findIndex((s) => s.id === sessionId);
    if (index >= 0) {
      this.list.select(index + 1); // +1 因为第一项是 "New Session"
      this.render();
    }
  }

  /**
   * 聚焦列表
   */
  focus(): void {
    this.list.focus();
  }

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

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

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