import { Component, Prop, State, h, Element, Watch, Event, EventEmitter } from '@stencil/core';

export interface ChatMessage {
  id: string;
  type: 'text' | 'markdown' | 'echarts' | string;
  content: string | any;
  timestamp?: number;
  isUser?: boolean;
  customRenderer?: string;
}

@Component({
  tag: 'ai-chat',
  styleUrl: './ai-chat.css',
  shadow: true,
})
export class AiChat {
  @Element() el: HTMLElement;

  /**
   * 聊天消息列表
   */
  @Prop() messages: ChatMessage[] = [];

  /**
   * 是否显示时间戳
   */
  @Prop() showTimestamp: boolean = true;

  /**
   * 是否显示用户头像
   */
  @Prop() showUserAvatar: boolean = true;

  /**
   * 是否显示AI头像
   */
  @Prop() showAiAvatar: boolean = true;

  /**
   * 用户头像URL
   */
  @Prop() userAvatar: string = '';

  /**
   * AI头像URL
   */
  @Prop() aiAvatar: string = '';

  /**
   * 自定义渲染器映射
   */
  @Prop() customRenderers: { [key: string]: string } = {};

  /**
   * 是否显示输入框
   */
  @Prop() showInput: boolean = true;

  /**
   * 输入框占位符
   */
  @Prop() inputPlaceholder: string = '输入消息...';

  /**
   * 是否禁用输入
   */
  @Prop() inputDisabled: boolean = false;

  /**
   * 最大输入长度
   */
  @Prop() maxInputLength: number = 1000;

  /**
   * 是否支持多行输入
   */
  @Prop() multilineInput: boolean = true;

  /**
   * 消息点击事件
   */
  @Event() messageClick: EventEmitter<ChatMessage>;

  /**
   * 消息长按事件
   */
  @Event() messageLongPress: EventEmitter<ChatMessage>;

  /**
   * 消息发送事件
   */
  @Event() messageSend: EventEmitter<{ content: string; timestamp: number }>;

  @State() private scrollToBottom: boolean = true;

  @Watch('messages')
  messagesChanged() {
    this.scrollToBottom = true;
  }

  private handleMessageInputSend = (event: CustomEvent<{ content: string; timestamp: number }>) => {
    this.messageSend.emit(event.detail);
  };

  componentDidUpdate() {
    if (this.scrollToBottom) {
      this.scrollToBottom = false;
      this.scrollToBottomOfChat();
    }
  }


  private scrollToBottomOfChat() {
    const chatContainer = this.el.shadowRoot?.querySelector('.chat-container');
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  }

  private handleMessageClick = (message: ChatMessage) => {
    this.messageClick.emit(message);
  };

  private handleMessageLongPress = (message: ChatMessage) => {
    this.messageLongPress.emit(message);
  };


  private renderMessage(message: ChatMessage) {
    const isUser = message.isUser;
    const messageClass = `message ${isUser ? 'user-message' : 'ai-message'}`;

    return (
      <div
        class={messageClass}
        onClick={() => this.handleMessageClick(message)}
        onTouchStart={() => {
          let timer: NodeJS.Timeout;
          timer = setTimeout(() => {
            this.handleMessageLongPress(message);
          }, 500);
          const handleTouchEnd = () => {
            clearTimeout(timer);
            document.removeEventListener('touchend', handleTouchEnd);
          };
          document.addEventListener('touchend', handleTouchEnd);
        }}
      >
        {!isUser && this.showAiAvatar && (
          <div class="avatar ai-avatar">
            {this.aiAvatar ? (
              <img src={this.aiAvatar} alt="AI" />
            ) : (
              <div class="default-avatar">AI</div>
            )}
          </div>
        )}
        
        <div class="message-content">
          <div class="message-bubble">
            {this.renderMessageContent(message)}
          </div>
          {this.showTimestamp && message.timestamp && (
            <div class="message-time">
              {new Date(message.timestamp).toLocaleTimeString()}
            </div>
          )}
        </div>

        {isUser && this.showUserAvatar && (
          <div class="avatar user-avatar">
            {this.userAvatar ? (
              <img src={this.userAvatar} alt="User" />
            ) : (
              <div class="default-avatar">U</div>
            )}
          </div>
        )}
      </div>
    );
  }

  private renderMessageContent(message: ChatMessage) {
    const { type, content, customRenderer } = message;

    // 检查是否有自定义渲染器
    if (customRenderer && this.customRenderers[customRenderer]) {
      const customTagName = this.customRenderers[customRenderer];
      return h(customTagName as any, { content });
    }

    // 根据类型渲染不同内容
    switch (type) {
      case 'text':
        return <internal-text-renderer content={content}></internal-text-renderer>;
      case 'markdown':
        return <internal-markdown-renderer content={content}></internal-markdown-renderer>;
      case 'echarts':
        return <internal-echarts-renderer content={content}></internal-echarts-renderer>;
      default:
        return <internal-text-renderer content={content}></internal-text-renderer>;
    }
  }

  render() {
    return (
      <div class="ai-chat">
        <div class="chat-container">
          {this.messages.map(message => (
            <div key={message.id}>
              {this.renderMessage(message)}
            </div>
          ))}
        </div>
        {this.showInput && (
          <internal-message-input
            placeholder={this.inputPlaceholder}
            disabled={this.inputDisabled}
            maxLength={this.maxInputLength}
            multiline={this.multilineInput}
            onMessageSend={this.handleMessageInputSend}
          />
        )}
      </div>
    );
  }
}
