import { LitElement, html, css, property, state, customElement } from './plugins.js';
import type { CSSResult, TemplateResult } from './plugins.js';
import { sharedStyles, panelStyles, tableStyles, buttonStyles } from './sw-dash-styles.js';

export interface IEventLogEntry {
  id: string;
  timestamp: number;
  type: string;
  message: string;
  details?: Record<string, any>;
}

type TEventFilter = 'all' | 'sw_installed' | 'sw_activated' | 'sw_updated' | 'sw_stopped'
  | 'speedtest_started' | 'speedtest_completed' | 'speedtest_failed'
  | 'backend_connected' | 'backend_disconnected'
  | 'cache_invalidated' | 'network_online' | 'network_offline'
  | 'update_check' | 'error';

/**
 * Events panel component for sw-dash
 *
 * Receives events via property from parent (sw-dash-app).
 * Filtering is done locally.
 * Load more and clear operations dispatch events to parent.
 */
@customElement('sw-dash-events')
export class SwDashEvents extends LitElement {
  public static styles: CSSResult[] = [
    sharedStyles,
    panelStyles,
    tableStyles,
    buttonStyles,
    css`
      :host {
        display: block;
      }

      .events-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: var(--space-4);
        gap: var(--space-3);
        flex-wrap: wrap;
      }

      .filter-group {
        display: flex;
        align-items: center;
        gap: var(--space-2);
      }

      .filter-label {
        font-size: 12px;
        color: var(--text-tertiary);
      }

      .filter-select {
        background: var(--bg-secondary);
        border: 1px solid var(--border-default);
        border-radius: var(--radius-sm);
        padding: var(--space-1) var(--space-2);
        color: var(--text-primary);
        font-size: 12px;
      }

      .filter-select:focus {
        outline: none;
        border-color: var(--accent-primary);
      }

      .events-list {
        display: flex;
        flex-direction: column;
        gap: var(--space-2);
        max-height: 600px;
        overflow-y: auto;
      }

      .event-card {
        background: var(--bg-secondary);
        border: 1px solid var(--border-default);
        border-radius: var(--radius-md);
        padding: var(--space-3);
      }

      .event-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: var(--space-2);
      }

      .event-type {
        display: inline-flex;
        align-items: center;
        padding: var(--space-1) var(--space-2);
        border-radius: var(--radius-sm);
        font-size: 11px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      .event-type.sw { background: rgba(99, 102, 241, 0.15); color: var(--accent-primary); }
      .event-type.speedtest { background: rgba(59, 130, 246, 0.15); color: #3b82f6; }
      .event-type.network { background: rgba(34, 197, 94, 0.15); color: var(--accent-success); }
      .event-type.cache { background: rgba(251, 191, 36, 0.15); color: var(--accent-warning); }
      .event-type.error { background: rgba(239, 68, 68, 0.15); color: var(--accent-error); }

      .event-time {
        font-size: 11px;
        color: var(--text-tertiary);
        font-variant-numeric: tabular-nums;
      }

      .event-message {
        font-size: 13px;
        color: var(--text-primary);
        margin-bottom: var(--space-2);
      }

      .event-details {
        font-size: 11px;
        color: var(--text-tertiary);
        background: var(--bg-tertiary);
        padding: var(--space-2);
        border-radius: var(--radius-sm);
        font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
        white-space: pre-wrap;
        word-break: break-all;
      }

      .stats-bar {
        display: flex;
        gap: var(--space-4);
        margin-bottom: var(--space-4);
        padding: var(--space-3);
        background: var(--bg-secondary);
        border-radius: var(--radius-md);
        border: 1px solid var(--border-default);
      }

      .stat-item {
        display: flex;
        flex-direction: column;
        gap: var(--space-1);
      }

      .stat-value {
        font-size: 18px;
        font-weight: 600;
        color: var(--text-primary);
        font-variant-numeric: tabular-nums;
      }

      .stat-label {
        font-size: 11px;
        color: var(--text-tertiary);
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      .empty-state {
        text-align: center;
        padding: var(--space-6);
        color: var(--text-tertiary);
      }

      .clear-btn {
        background: rgba(239, 68, 68, 0.1);
        color: var(--accent-error);
        border: 1px solid transparent;
      }

      .clear-btn:hover {
        background: rgba(239, 68, 68, 0.2);
        border-color: var(--accent-error);
      }

      .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: var(--space-2);
        margin-top: var(--space-4);
      }

      .page-info {
        font-size: 12px;
        color: var(--text-tertiary);
      }
    `
  ];

  // Received from parent (sw-dash-app)
  @property({ type: Array }) accessor events: IEventLogEntry[] = [];
  @property({ type: Number }) accessor totalCount = 0;

  // Local state for filtering
  @state() accessor filter: TEventFilter = 'all';
  @state() accessor searchText = '';
  @state() accessor isLoadingMore = false;

  private handleFilterChange(e: Event): void {
    this.filter = (e.target as HTMLSelectElement).value as TEventFilter;
    // Local filtering - no HTTP request
  }

  private handleSearch(e: Event): void {
    this.searchText = (e.target as HTMLInputElement).value.toLowerCase();
  }

  private handleClear(): void {
    if (!confirm('Are you sure you want to clear the event log? This cannot be undone.')) {
      return;
    }
    // Dispatch event to parent to clear via DeesComms
    this.dispatchEvent(new CustomEvent('clear-events', {
      bubbles: true,
      composed: true,
    }));
  }

  private loadMore(): void {
    if (this.isLoadingMore || this.events.length === 0) return;

    this.isLoadingMore = true;
    const oldestEvent = this.events[this.events.length - 1];

    // Dispatch event to parent to load more via DeesComms
    this.dispatchEvent(new CustomEvent('load-more-events', {
      detail: { before: oldestEvent.timestamp },
      bubbles: true,
      composed: true,
    }));

    // Reset loading state after a short delay (parent will update events prop)
    setTimeout(() => {
      this.isLoadingMore = false;
    }, 1000);
  }

  private getTypeClass(type: string): string {
    if (type.startsWith('sw_')) return 'sw';
    if (type.startsWith('speedtest_')) return 'speedtest';
    if (type.startsWith('network_') || type.startsWith('backend_')) return 'network';
    if (type.startsWith('cache_') || type === 'update_check') return 'cache';
    if (type === 'error') return 'error';
    return 'sw';
  }

  private formatTimestamp(ts: number): string {
    const date = new Date(ts);
    return date.toLocaleString();
  }

  private formatTypeLabel(type: string): string {
    return type.replace(/_/g, ' ');
  }

  /**
   * Filter events locally based on type and search text
   */
  private getFilteredEvents(): IEventLogEntry[] {
    let result = this.events;

    // Filter by type
    if (this.filter !== 'all') {
      result = result.filter(e => e.type === this.filter);
    }

    // Filter by search text
    if (this.searchText) {
      result = result.filter(e =>
        e.message.toLowerCase().includes(this.searchText) ||
        e.type.toLowerCase().includes(this.searchText) ||
        (e.details && JSON.stringify(e.details).toLowerCase().includes(this.searchText))
      );
    }

    return result;
  }

  public render(): TemplateResult {
    const filteredEvents = this.getFilteredEvents();

    return html`
      <div class="stats-bar">
        <div class="stat-item">
          <span class="stat-value">${this.totalCount}</span>
          <span class="stat-label">Total Events</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">${filteredEvents.length}</span>
          <span class="stat-label">Showing</span>
        </div>
      </div>

      <div class="events-header">
        <div class="filter-group">
          <span class="filter-label">Filter:</span>
          <select class="filter-select" @change="${this.handleFilterChange}">
            <option value="all">All Events</option>
            <option value="sw_installed">SW Installed</option>
            <option value="sw_activated">SW Activated</option>
            <option value="sw_updated">SW Updated</option>
            <option value="speedtest_started">Speedtest Started</option>
            <option value="speedtest_completed">Speedtest Completed</option>
            <option value="speedtest_failed">Speedtest Failed</option>
            <option value="network_online">Network Online</option>
            <option value="network_offline">Network Offline</option>
            <option value="cache_invalidated">Cache Invalidated</option>
            <option value="error">Errors</option>
          </select>
          <input
            type="text"
            class="search-input"
            placeholder="Search events..."
            .value="${this.searchText}"
            @input="${this.handleSearch}"
            style="width: 200px;"
          >
        </div>
        <button class="btn clear-btn" @click="${this.handleClear}">Clear Log</button>
      </div>

      ${this.events.length === 0 ? html`
        <div class="empty-state">No events recorded</div>
      ` : filteredEvents.length === 0 ? html`
        <div class="empty-state">No events match filter</div>
      ` : html`
        <div class="events-list">
          ${filteredEvents.map(event => html`
            <div class="event-card">
              <div class="event-header">
                <span class="event-type ${this.getTypeClass(event.type)}">${this.formatTypeLabel(event.type)}</span>
                <span class="event-time">${this.formatTimestamp(event.timestamp)}</span>
              </div>
              <div class="event-message">${event.message}</div>
              ${event.details ? html`
                <div class="event-details">${JSON.stringify(event.details, null, 2)}</div>
              ` : ''}
            </div>
          `)}
        </div>

        ${this.events.length < this.totalCount ? html`
          <div class="pagination">
            <button class="btn btn-secondary" @click="${this.loadMore}" ?disabled="${this.isLoadingMore}">
              ${this.isLoadingMore ? 'Loading...' : 'Load More'}
            </button>
            <span class="page-info">${this.events.length} of ${this.totalCount} events</span>
          </div>
        ` : ''}
      `}
    `;
  }
}
