import * as plugins from '../plugins.js';
import { apiService, type IDatabaseStats } from '../services/index.js';
import { formatSize, formatCount } from '../utilities/index.js';
import { themeStyles } from '../styles/index.js';

const { html, css, cssManager, customElement, property, state, DeesElement } = plugins;

@customElement('tsview-mongo-db-overview')
export class TsviewMongoDbOverview extends DeesElement {
  @property({ type: String })
  public accessor databaseName: string = '';

  @state()
  private accessor stats: IDatabaseStats | null = null;

  @state()
  private accessor loading: boolean = false;

  @state()
  private accessor error: string = '';

  public static styles = [
    cssManager.defaultStyles,
    themeStyles,
    css`
      :host {
        display: block;
        height: 100%;
      }

      .overview-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        padding: 24px;
        box-sizing: border-box;
        overflow: auto;
      }

      .header {
        margin-bottom: 24px;
      }

      .header-title {
        font-size: 24px;
        font-weight: 600;
        color: #fff;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
      }

      .header-title svg {
        width: 28px;
        height: 28px;
        color: #888;
      }

      .header-subtitle {
        color: #888;
        font-size: 14px;
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 32px;
      }

      .stat-card {
        background: rgba(255, 255, 255, 0.03);
        border: 1px solid #333;
        border-radius: 8px;
        padding: 16px;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .stat-label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #888;
      }

      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #e0e0e0;
      }

      .stat-value.small {
        font-size: 18px;
      }

      .stat-description {
        font-size: 11px;
        color: #666;
      }

      .section {
        margin-bottom: 24px;
      }

      .section-title {
        font-size: 14px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #666;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #333;
      }

      .loading-state {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #888;
        font-size: 14px;
      }

      .error-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #f87171;
        text-align: center;
      }

      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #666;
        text-align: center;
      }

      .empty-state svg {
        width: 48px;
        height: 48px;
        margin-bottom: 12px;
        opacity: 0.5;
      }
    `,
  ];

  updated(changedProperties: Map<string, unknown>) {
    if (changedProperties.has('databaseName') && this.databaseName) {
      this.loadStats();
    }
  }

  async connectedCallback() {
    super.connectedCallback();
    if (this.databaseName) {
      await this.loadStats();
    }
  }

  private async loadStats() {
    if (!this.databaseName) return;

    this.loading = true;
    this.error = '';

    try {
      this.stats = await apiService.getDatabaseStats(this.databaseName);
    } catch (err) {
      console.error('Error loading database stats:', err);
      this.error = 'Failed to load database statistics';
    }

    this.loading = false;
  }

  render() {
    if (!this.databaseName) {
      return html`
        <div class="overview-container">
          <div class="empty-state">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <ellipse cx="12" cy="5" rx="9" ry="3"></ellipse>
              <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path>
              <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path>
            </svg>
            <p>Select a database to view overview</p>
          </div>
        </div>
      `;
    }

    if (this.loading) {
      return html`
        <div class="overview-container">
          <div class="loading-state">Loading database statistics...</div>
        </div>
      `;
    }

    if (this.error) {
      return html`
        <div class="overview-container">
          <div class="error-state">${this.error}</div>
        </div>
      `;
    }

    if (!this.stats) {
      return html`
        <div class="overview-container">
          <div class="empty-state">
            <p>No statistics available</p>
          </div>
        </div>
      `;
    }

    return html`
      <div class="overview-container">
        <div class="header">
          <h1 class="header-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <ellipse cx="12" cy="5" rx="9" ry="3"></ellipse>
              <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path>
              <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path>
            </svg>
            ${this.databaseName}
          </h1>
          <p class="header-subtitle">Database Overview</p>
        </div>

        <div class="section">
          <div class="section-title">Storage</div>
          <div class="stats-grid">
            <div class="stat-card">
              <span class="stat-label">Collections</span>
              <span class="stat-value">${this.stats.collections}</span>
              <span class="stat-description">Total collections in database</span>
            </div>
            <div class="stat-card">
              <span class="stat-label">Documents</span>
              <span class="stat-value">${formatCount(this.stats.objects) || this.stats.objects}</span>
              <span class="stat-description">Total documents stored</span>
            </div>
            <div class="stat-card">
              <span class="stat-label">Avg Document Size</span>
              <span class="stat-value small">${formatSize(this.stats.avgObjSize)}</span>
              <span class="stat-description">Average size per document</span>
            </div>
            <div class="stat-card">
              <span class="stat-label">Data Size</span>
              <span class="stat-value small">${formatSize(this.stats.dataSize)}</span>
              <span class="stat-description">Uncompressed data size</span>
            </div>
            <div class="stat-card">
              <span class="stat-label">Storage Size</span>
              <span class="stat-value small">${formatSize(this.stats.storageSize)}</span>
              <span class="stat-description">Allocated storage</span>
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">Indexes</div>
          <div class="stats-grid">
            <div class="stat-card">
              <span class="stat-label">Index Count</span>
              <span class="stat-value">${this.stats.indexes}</span>
              <span class="stat-description">Total indexes in database</span>
            </div>
            <div class="stat-card">
              <span class="stat-label">Index Size</span>
              <span class="stat-value small">${formatSize(this.stats.indexSize)}</span>
              <span class="stat-description">Total index storage</span>
            </div>
          </div>
        </div>
      </div>
    `;
  }
}
