import {
  DeesElement,
  customElement,
  html,
  css,
  cssManager,
  property,
  type TemplateResult,
} from '@design.estate/dees-element';

import './sz-stat-card.js';

declare global {
  interface HTMLElementTagNameMap {
    'sz-network-proxy-view': SzNetworkProxyView;
  }
}

export interface ITrafficTarget {
  type: 'service' | 'registry' | 'platform';
  name: string;
  domain: string | null;
  target: string;
  status: 'running' | 'stopped';
}

export interface IAccessLogEntry {
  timestamp: string;
  method: string;
  path: string;
  status: number;
  duration: number;
  ip: string;
}

@customElement('sz-network-proxy-view')
export class SzNetworkProxyView extends DeesElement {
  public static demo = () => html`
    <div style="padding: 24px; max-width: 1400px;">
      <sz-network-proxy-view
        proxyStatus="running"
        routeCount="3"
        certificateCount="2"
        targetCount="11"
        .targets=${[
          { type: 'service', name: 'test-nginx', domain: 'app.bleu.de', target: 'localhost:8080', status: 'running' },
          { type: 'service', name: 'hello-world', domain: 'hello.task.vc', target: 'localhost:8081', status: 'running' },
          { type: 'registry', name: 'onebox-registry', domain: null, target: 'localhost:4000', status: 'running' },
          { type: 'platform', name: 'MongoDB', domain: null, target: 'localhost:27017', status: 'running' },
          { type: 'platform', name: 'ClickHouse', domain: null, target: 'localhost:8123', status: 'running' },
        ]}
        .logs=${[
          { timestamp: '2024-01-02 10:15:32', method: 'GET', path: '/api/services', status: 200, duration: 45, ip: '192.168.1.100' },
          { timestamp: '2024-01-02 10:15:30', method: 'POST', path: '/api/auth/login', status: 200, duration: 120, ip: '192.168.1.101' },
          { timestamp: '2024-01-02 10:15:28', method: 'GET', path: '/static/bundle.js', status: 304, duration: 5, ip: '192.168.1.100' },
        ]}
      ></sz-network-proxy-view>
    </div>
  `;

  @property({ type: String })
  public accessor proxyStatus: 'running' | 'stopped' = 'stopped';

  @property({ type: String })
  public accessor routeCount: string = '0';

  @property({ type: String })
  public accessor certificateCount: string = '0';

  @property({ type: String })
  public accessor targetCount: string = '0';

  @property({ type: Array })
  public accessor targets: ITrafficTarget[] = [];

  @property({ type: Array })
  public accessor logs: IAccessLogEntry[] = [];

  @property({ type: Boolean })
  public accessor streaming: boolean = false;

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

      .actions {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 16px;
      }

      .refresh-button {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: ${cssManager.bdTheme('#ffffff', '#09090b')};
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        cursor: pointer;
        transition: all 200ms ease;
      }

      .refresh-button:hover {
        background: ${cssManager.bdTheme('#f4f4f5', '#18181b')};
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        margin-bottom: 24px;
      }

      @media (min-width: 768px) {
        .stats-grid {
          grid-template-columns: repeat(4, 1fr);
        }
      }

      .section {
        background: ${cssManager.bdTheme('#ffffff', '#09090b')};
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        border-radius: 8px;
        margin-bottom: 24px;
        overflow: hidden;
      }

      .section-header {
        padding: 16px;
        border-bottom: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .section-subtitle {
        font-size: 13px;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        margin-top: 2px;
      }

      .table-header {
        display: grid;
        grid-template-columns: 80px 1.5fr 1.5fr 1.5fr 80px;
        gap: 16px;
        padding: 12px 16px;
        background: ${cssManager.bdTheme('#f4f4f5', '#18181b')};
        border-bottom: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }

      .table-row {
        display: grid;
        grid-template-columns: 80px 1.5fr 1.5fr 1.5fr 80px;
        gap: 16px;
        padding: 12px 16px;
        border-bottom: 1px solid ${cssManager.bdTheme('#f4f4f5', '#27272a')};
        font-size: 14px;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        cursor: pointer;
        transition: background 200ms ease;
      }

      .table-row:last-child {
        border-bottom: none;
      }

      .table-row:hover {
        background: ${cssManager.bdTheme('#f4f4f5', '#18181b')};
      }

      .type-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
      }

      .type-badge.service {
        background: ${cssManager.bdTheme('#dbeafe', 'rgba(59, 130, 246, 0.2)')};
        color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
      }

      .type-badge.registry {
        background: ${cssManager.bdTheme('#f3e8ff', 'rgba(168, 85, 247, 0.2)')};
        color: ${cssManager.bdTheme('#9333ea', '#a855f7')};
      }

      .type-badge.platform {
        background: ${cssManager.bdTheme('#fef3c7', 'rgba(245, 158, 11, 0.2)')};
        color: ${cssManager.bdTheme('#d97706', '#f59e0b')};
      }

      .target-value {
        font-family: monospace;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }

      .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 9999px;
        font-size: 12px;
        font-weight: 500;
      }

      .status-badge.running {
        background: ${cssManager.bdTheme('#dcfce7', 'rgba(34, 197, 94, 0.2)')};
        color: ${cssManager.bdTheme('#16a34a', '#22c55e')};
      }

      .status-badge.stopped {
        background: ${cssManager.bdTheme('#fee2e2', 'rgba(239, 68, 68, 0.2)')};
        color: ${cssManager.bdTheme('#dc2626', '#ef4444')};
      }

      .logs-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
      }

      .logs-actions {
        display: flex;
        gap: 8px;
      }

      .stream-button {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        background: ${cssManager.bdTheme('#2563eb', '#3b82f6')};
        border: none;
        border-radius: 4px;
        font-size: 13px;
        font-weight: 500;
        color: white;
        cursor: pointer;
        transition: all 200ms ease;
      }

      .stream-button:hover {
        background: ${cssManager.bdTheme('#1d4ed8', '#2563eb')};
      }

      .stream-button.streaming {
        background: ${cssManager.bdTheme('#dc2626', '#ef4444')};
      }

      .stream-button.streaming:hover {
        background: ${cssManager.bdTheme('#b91c1c', '#dc2626')};
      }

      .clear-button {
        padding: 6px 12px;
        background: transparent;
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        border-radius: 4px;
        font-size: 13px;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        cursor: pointer;
        transition: all 200ms ease;
      }

      .clear-button:hover {
        background: ${cssManager.bdTheme('#f4f4f5', '#18181b')};
      }

      .logs-container {
        padding: 16px;
        font-family: monospace;
        font-size: 13px;
        max-height: 300px;
        overflow-y: auto;
        background: ${cssManager.bdTheme('#fafafa', '#0a0a0a')};
      }

      .log-entry {
        padding: 4px 0;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }

      .log-timestamp {
        color: ${cssManager.bdTheme('#a1a1aa', '#52525b')};
      }

      .log-method {
        font-weight: 600;
        color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
      }

      .log-status-2xx {
        color: ${cssManager.bdTheme('#16a34a', '#22c55e')};
      }

      .log-status-3xx {
        color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
      }

      .log-status-4xx {
        color: ${cssManager.bdTheme('#ca8a04', '#facc15')};
      }

      .log-status-5xx {
        color: ${cssManager.bdTheme('#dc2626', '#ef4444')};
      }

      .empty-logs {
        padding: 24px;
        text-align: center;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }
    `,
  ];

  public render(): TemplateResult {
    return html`
      <div class="actions">
        <button class="refresh-button" @click=${() => this.handleRefresh()}>Refresh</button>
      </div>

      <div class="stats-grid">
        <sz-stat-card
          label="Proxy Status"
          value="${this.proxyStatus === 'running' ? 'Running' : 'Stopped'}"
          icon="server"
          variant="${this.proxyStatus === 'running' ? 'success' : 'error'}"
          valueBadge
        ></sz-stat-card>
        <sz-stat-card
          label="Routes"
          value="${this.routeCount}"
          icon="server"
        ></sz-stat-card>
        <sz-stat-card
          label="Certificates"
          value="${this.certificateCount}"
          icon="check"
        ></sz-stat-card>
        <sz-stat-card
          label="Targets"
          value="${this.targetCount}"
          icon="server"
        ></sz-stat-card>
      </div>

      <div class="section">
        <div class="section-header">
          <div class="section-title">Traffic Targets</div>
          <div class="section-subtitle">Services, registry, and platform services with their routing info</div>
        </div>
        <div class="table-header">
          <span>Type</span>
          <span>Name</span>
          <span>Domain</span>
          <span>Target</span>
          <span>Status</span>
        </div>
        ${this.targets.map(target => html`
          <div class="table-row" @click=${() => this.handleTargetClick(target)}>
            <span><span class="type-badge ${target.type}">${target.type}</span></span>
            <span>${target.name}</span>
            <span>${target.domain || '-'}</span>
            <span class="target-value">${target.target}</span>
            <span><span class="status-badge ${target.status}">${target.status}</span></span>
          </div>
        `)}
      </div>

      <div class="section">
        <div class="logs-header">
          <div>
            <div class="section-title">Access Logs</div>
            <div class="section-subtitle">Real-time Caddy access logs</div>
          </div>
          <div class="logs-actions">
            <button class="stream-button ${this.streaming ? 'streaming' : ''}" @click=${() => this.toggleStreaming()}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                ${this.streaming
                  ? html`<rect x="6" y="6" width="12" height="12" rx="1"/>`
                  : html`<polygon points="5,3 19,12 5,21"/>`
                }
              </svg>
              ${this.streaming ? 'Stop' : 'Stream'}
            </button>
            <button class="clear-button" @click=${() => this.handleClearLogs()}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="3,6 5,6 21,6"/><path d="M19,6v14a2,2,0,0,1-2,2H7a2,2,0,0,1-2-2V6m3,0V4a2,2,0,0,1,2-2h4a2,2,0,0,1,2,2v2"/>
              </svg>
              Clear logs
            </button>
          </div>
        </div>
        <div class="logs-container">
          ${this.logs.length > 0 ? this.logs.map(log => html`
            <div class="log-entry">
              <span class="log-timestamp">${log.timestamp}</span>
              <span class="log-method">${log.method}</span>
              ${log.path}
              <span class="${this.getStatusClass(log.status)}">${log.status}</span>
              ${log.duration}ms
              ${log.ip}
            </div>
          `) : html`
            <div class="empty-logs">Click "Stream" to start live access log streaming</div>
          `}
        </div>
      </div>
    `;
  }

  private getStatusClass(status: number): string {
    if (status >= 500) return 'log-status-5xx';
    if (status >= 400) return 'log-status-4xx';
    if (status >= 300) return 'log-status-3xx';
    return 'log-status-2xx';
  }

  private handleRefresh() {
    this.dispatchEvent(new CustomEvent('refresh', { bubbles: true, composed: true }));
  }

  private handleTargetClick(target: ITrafficTarget) {
    this.dispatchEvent(new CustomEvent('target-click', { detail: target, bubbles: true, composed: true }));
  }

  private toggleStreaming() {
    this.streaming = !this.streaming;
    this.dispatchEvent(new CustomEvent('stream-toggle', { detail: { streaming: this.streaming }, bubbles: true, composed: true }));
  }

  private handleClearLogs() {
    this.dispatchEvent(new CustomEvent('clear-logs', { bubbles: true, composed: true }));
  }
}
