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

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>
  `;

  public static demoGroups = ['Network'];

  @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')};
      }

      dees-statsgrid {
        display: block;
        margin-bottom: 24px;
      }

      dees-tile {
        display: block;
        margin-bottom: 24px;
      }

      .section-header {
        height: 36px;
        display: flex;
        align-items: center;
        padding: 0 16px;
        width: 100%;
        box-sizing: border-box;
      }

      .section-heading {
        flex: 1;
        display: flex;
        align-items: baseline;
        gap: 8px;
        min-width: 0;
      }

      .section-title {
        font-weight: 500;
        font-size: 13px;
        letter-spacing: -0.01em;
        color: var(--dees-color-text-secondary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .section-subtitle {
        font-size: 12px;
        color: var(--dees-color-text-muted);
        letter-spacing: -0.01em;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .section-footer {
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        align-items: center;
        gap: 0;
        height: 36px;
        width: 100%;
        box-sizing: border-box;
      }

      .tile-button {
        padding: 0 16px;
        height: 100%;
        text-align: center;
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        user-select: none;
        transition: all 0.15s ease;
        background: transparent;
        border: none;
        border-left: 1px solid var(--dees-color-border-subtle);
        color: var(--dees-color-text-muted);
        white-space: nowrap;
        display: flex;
        align-items: center;
        gap: 6px;
      }

      .tile-button:first-child {
        border-left: none;
      }

      .tile-button:hover {
        background: var(--dees-color-hover);
        color: var(--dees-color-text-primary);
      }

      .tile-button.primary {
        color: ${cssManager.bdTheme('hsl(217.2 91.2% 59.8%)', 'hsl(213.1 93.9% 67.8%)')};
        font-weight: 600;
      }

      .tile-button.primary:hover {
        background: ${cssManager.bdTheme('hsl(217.2 91.2% 59.8% / 0.08)', 'hsl(213.1 93.9% 67.8% / 0.08)')};
        color: ${cssManager.bdTheme('hsl(217.2 91.2% 50%)', 'hsl(213.1 93.9% 75%)')};
      }

      .tile-button.danger {
        color: ${cssManager.bdTheme('#dc2626', '#ef4444')};
      }

      .tile-button.danger:hover {
        background: ${cssManager.bdTheme('#fee2e2', 'rgba(239, 68, 68, 0.1)')};
      }

      .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-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')};
      }
    `,
  ];

  private get tiles(): IStatsTile[] {
    return [
      {
        id: 'proxy-status',
        title: 'Proxy Status',
        value: this.proxyStatus === 'running' ? 'Running' : 'Stopped',
        type: 'text',
        icon: 'lucide:server',
        color: this.proxyStatus === 'running' ? '#22c55e' : '#ef4444',
      },
      {
        id: 'routes',
        title: 'Routes',
        value: this.routeCount,
        type: 'number',
        icon: 'lucide:server',
      },
      {
        id: 'certificates',
        title: 'Certificates',
        value: this.certificateCount,
        type: 'number',
        icon: 'lucide:check',
      },
      {
        id: 'targets',
        title: 'Targets',
        value: this.targetCount,
        type: 'number',
        icon: 'lucide:server',
      },
    ];
  }

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

      <dees-statsgrid
        .tiles=${this.tiles}
        .minTileWidth=${200}
      ></dees-statsgrid>

      <dees-tile>
        <div slot="header" class="section-header">
          <div class="section-heading">
            <span class="section-title">Traffic Targets</span>
            <span class="section-subtitle">Services, registry, and platform services with their routing info</span>
          </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>
        `)}
      </dees-tile>

      <dees-tile>
        <div slot="header" class="section-header">
          <div class="section-heading">
            <span class="section-title">Access Logs</span>
            <span class="section-subtitle">Real-time Caddy access logs</span>
          </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 slot="footer" class="section-footer">
          <button class="tile-button ${this.streaming ? 'danger' : 'primary'}" @click=${() => this.toggleStreaming()}>
            <svg width="12" height="12" 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="tile-button" @click=${() => this.handleClearLogs()}>
            <svg width="12" height="12" 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>
      </dees-tile>
    `;
  }

  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 }));
  }
}
