import { Component, Prop, State, Event, EventEmitter, h, Element, Watch, Fragment } from '@stencil/core';
import { ApiService } from '../../services/api.service';
import { ChatStorageService } from '../../services/chat-storage.service';
import { BackendMessage, ChatListItem, PaginatedMessagesResponse } from '../../types/api';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/pl';
import 'dayjs/locale/en';

dayjs.extend(relativeTime);

@Component({
  tag: 'bcx-chat-list',
  styleUrl: 'bcx-chat-list.scss',
  shadow: true,
})
export class BcxChatList {
  @Element() el: HTMLElement;

  @Prop() apiService: ApiService;
  @Prop() language: 'pl' | 'en' = 'en';
  @Prop() theme: 'light' | 'dark' = 'light';

  @State() chats: ChatListItem[] = [];
  @State() selectedChatId: string | null = null;
  @State() messages: BackendMessage[] = [];
  @State() isLoading: boolean = false;
  @State() isLoadingMore: boolean = false;
  @State() hasMore: boolean = false;
  @State() currentPage: number = 1;
  @State() error: string | null = null;

  @Event() chatSelected: EventEmitter<string>;
  @Event() close: EventEmitter<void>;

  private messagesContainerRef: HTMLDivElement;
  private observer: IntersectionObserver | null = null;
  private loadMoreTriggerRef: HTMLDivElement;
  private pageSize: number = 20;

  @Watch('language')
  async onLanguageChange() {
    // Set dayjs locale based on language prop
    dayjs.locale(this.language === 'pl' ? 'pl' : 'en');
  }

  componentWillLoad() {
    // Set initial dayjs locale
    dayjs.locale(this.language === 'pl' ? 'pl' : 'en');
    this.loadChats();
  }

  componentDidLoad() {
    // Setup infinite scroll after messages are loaded
    if (this.selectedChatId) {
      // OPTYMALIZACJA: Użycie requestAnimationFrame zamiast setTimeout
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          this.setupInfiniteScroll();
        });
      });
    }
  }

  componentDidUpdate() {
    // Re-setup infinite scroll when selected chat changes
    if (this.selectedChatId && this.messages.length > 0) {
      // OPTYMALIZACJA: Użycie requestAnimationFrame zamiast setTimeout
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          this.setupInfiniteScroll();
        });
      });
    }
  }

  disconnectedCallback() {
    if (this.observer) {
      this.observer.disconnect();
    }
  }

  private loadChats() {
    this.chats = ChatStorageService.getChats();
  }

  private async selectChat(chatId: string) {
    if (this.selectedChatId === chatId) {
      return;
    }

    // Cleanup previous observer
    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }

    this.selectedChatId = chatId;
    this.messages = [];
    this.currentPage = 1;
    this.hasMore = false;
    this.error = null;

    await this.loadMessages(chatId, 1);

    // OPTYMALIZACJA: Użycie requestAnimationFrame zamiast setTimeout
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        this.setupInfiniteScroll();
      });
    });
  }

  private async loadMessages(chatId: string, page: number) {
    if (page === 1) {
      this.isLoading = true;
    } else {
      this.isLoadingMore = true;
    }

    try {
      const response: PaginatedMessagesResponse = await this.apiService.getChatMessages(chatId, page, this.pageSize);

      if (page === 1) {
        this.messages = response.results;
      } else {
        // Append older messages at the top (since we're loading backwards)
        this.messages = [...response.results, ...this.messages];
      }

      this.hasMore = response.has_next;
      this.currentPage = page;
    } catch (error) {
      this.error = error.message || 'Failed to load messages';
      console.error('[ChatList] Error loading messages:', error);
    } finally {
      this.isLoading = false;
      this.isLoadingMore = false;
    }
  }

  private async loadMoreMessages() {
    if (!this.selectedChatId || this.isLoadingMore || !this.hasMore) {
      return;
    }

    await this.loadMessages(this.selectedChatId, this.currentPage + 1);
  }

  private setupInfiniteScroll() {
    if (!this.loadMoreTriggerRef) {
      return;
    }

    this.observer = new IntersectionObserver(
      entries => {
        if (entries[0].isIntersecting && this.hasMore && !this.isLoadingMore) {
          this.loadMoreMessages();
        }
      },
      {
        root: this.messagesContainerRef,
        rootMargin: '100px',
        threshold: 0.1,
      },
    );

    this.observer.observe(this.loadMoreTriggerRef);
  }

  private formatMessageTime(timestamp: string): string {
    // Determine locale based on current language
    const locale = this.language === 'pl' ? 'pl' : 'en';

    // Use dayjs with locale directly on the instance
    // dayjs automatically handles locale loading if imported
    return dayjs(timestamp).locale(locale).fromNow();
  }

  private formatChatTime(timestamp: string): string {
    // Determine locale based on current language
    const locale = this.language === 'pl' ? 'pl' : 'en';

    // Use dayjs with locale directly on the instance
    // dayjs automatically handles locale loading if imported
    return dayjs(timestamp).locale(locale).fromNow();
  }

  private truncateMessage(message: string, maxLength: number = 60): string {
    if (message.length <= maxLength) {
      return message;
    }
    return message.substring(0, maxLength) + '...';
  }

  private handleBackClick = () => {
    this.selectedChatId = null;
    this.messages = [];
    this.currentPage = 1;
    this.hasMore = false;
  };

  private handleChatClick = (chatId: string) => {
    this.selectChat(chatId);
    this.chatSelected.emit(chatId);
  };

  private handleCloseClick = () => {
    this.close.emit();
  };

  render() {
    if (this.selectedChatId) {
      return (
        <div class={`bcx-chat-list bcx-chat-list--${this.theme}`} data-adblock-bypass="true">
          {/* Header */}
          <div class="bcx-chat-list__header">
            <button class="bcx-chat-list__back-btn" onClick={this.handleBackClick} aria-label="Back to chat list" data-adblock-bypass="true">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M19 12H5M12 19l-7-7 7-7" />
              </svg>
            </button>
            <h3 class="bcx-chat-list__header-title">{this.language === 'pl' ? 'Wiadomości' : 'Messages'}</h3>
            <button class="bcx-chat-list__close-btn" onClick={this.handleCloseClick} aria-label="Close" data-adblock-bypass="true">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>

          {/* Messages */}
          <div class="bcx-chat-list__messages" ref={el => (this.messagesContainerRef = el)} data-adblock-bypass="true">
            {this.isLoading && this.messages.length === 0 ? (
              <div class="bcx-chat-list__loading">
                <div class="bcx-chat-list__spinner"></div>
                <span>{this.language === 'pl' ? 'Ładowanie...' : 'Loading...'}</span>
              </div>
            ) : this.error ? (
              <div class="bcx-chat-list__error">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="12" cy="12" r="10"></circle>
                  <line x1="12" y1="8" x2="12" y2="12"></line>
                  <line x1="12" y1="16" x2="12.01" y2="16"></line>
                </svg>
                <p>{this.error}</p>
              </div>
            ) : (
              <Fragment>
                {/* Load more trigger */}
                {this.hasMore && (
                  <div ref={el => (this.loadMoreTriggerRef = el)} class="bcx-chat-list__load-more-trigger">
                    {this.isLoadingMore && (
                      <div class="bcx-chat-list__loading-more">
                        <div class="bcx-chat-list__spinner"></div>
                      </div>
                    )}
                  </div>
                )}

                {this.messages.map(message => (
                  <div key={message.id} class={`bcx-chat-list__message bcx-chat-list__message--${message.author === 'user' ? 'user' : 'assistant'}`} data-adblock-bypass="true">
                    <div class="bcx-chat-list__message-content">
                      <div class="bcx-chat-list__message-text">{message.content}</div>
                      <div class="bcx-chat-list__message-time">{this.formatMessageTime(message.created_at)}</div>
                    </div>
                  </div>
                ))}
              </Fragment>
            )}
          </div>
        </div>
      );
    }

    return (
      <div class={`bcx-chat-list bcx-chat-list--${this.theme}`} data-adblock-bypass="true">
        {/* Header */}
        <div class="bcx-chat-list__header">
          <h3 class="bcx-chat-list__header-title">{this.language === 'pl' ? 'Wszystkie konwersacje' : 'All conversations'}</h3>
          <button class="bcx-chat-list__close-btn" onClick={this.handleCloseClick} aria-label="Close" data-adblock-bypass="true">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>

        {/* Chat List */}
        <div class="bcx-chat-list__list" data-adblock-bypass="true">
          {this.chats.length === 0 ? (
            <div class="bcx-chat-list__empty">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
              </svg>
              <p>{this.language === 'pl' ? 'Brak konwersacji' : 'No conversations yet'}</p>
            </div>
          ) : (
            this.chats.map(chat => (
              <button key={chat.chatId} class="bcx-chat-list__item" onClick={() => this.handleChatClick(chat.chatId)} data-adblock-bypass="true">
                <div class="bcx-chat-list__item-content">
                  <div class="bcx-chat-list__item-message">{this.truncateMessage(chat.lastMessage)}</div>
                  <div class="bcx-chat-list__item-time">{this.formatChatTime(chat.lastMessageTimestamp)}</div>
                </div>
                <svg
                  class="bcx-chat-list__item-icon"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M5 12h14M12 5l7 7-7 7"></path>
                </svg>
              </button>
            ))
          )}
        </div>
      </div>
    );
  }
}
