import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { ApiService } from '../../../core/services/api.service';

interface ApplicationLog {
  id: string;
  level: 'INFO' | 'WARN' | 'ERROR';
  module: string;
  message: string;
  metadata?: any;
  createdAt: string;
}

interface PaginatedResponse {
  data: ApplicationLog[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

@Component({
  selector: 'app-logs-viewer',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatCardModule,
    MatTableModule,
    MatPaginatorModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
  ],
  template: `
    <mat-card>
      <mat-card-header>
        <mat-card-title>
          <mat-icon class="title-icon">description</mat-icon>
          Application Logs
        </mat-card-title>
        <div class="header-actions">
          <button mat-icon-button (click)="loadLogs()" [disabled]="loading" matTooltip="Refresh">
            <mat-icon>refresh</mat-icon>
          </button>
          <button mat-icon-button (click)="exportLogs()" [disabled]="loading || logs.length === 0" matTooltip="Export to JSON">
            <mat-icon>download</mat-icon>
          </button>
        </div>
      </mat-card-header>

      <mat-card-content>
        <!-- Filters -->
        <form [formGroup]="filterForm" class="filters">
          <mat-form-field appearance="outline" class="filter-field">
            <mat-label>Log Level</mat-label>
            <mat-select formControlName="level" (selectionChange)="applyFilters()">
              <mat-option value="">All Levels</mat-option>
              <mat-option value="INFO">INFO</mat-option>
              <mat-option value="WARN">WARN</mat-option>
              <mat-option value="ERROR">ERROR</mat-option>
            </mat-select>
          </mat-form-field>

          <mat-form-field appearance="outline" class="filter-field">
            <mat-label>Module</mat-label>
            <input matInput formControlName="module" placeholder="e.g., AuthService" (keyup.enter)="applyFilters()" />
            <button mat-icon-button matSuffix (click)="clearFilter('module')" *ngIf="filterForm.get('module')?.value">
              <mat-icon>clear</mat-icon>
            </button>
          </mat-form-field>

          <mat-form-field appearance="outline" class="filter-field filter-search">
            <mat-label>Search</mat-label>
            <input matInput formControlName="search" placeholder="Search in messages..." (keyup.enter)="applyFilters()" />
            <mat-icon matPrefix>search</mat-icon>
            <button mat-icon-button matSuffix (click)="clearFilter('search')" *ngIf="filterForm.get('search')?.value">
              <mat-icon>clear</mat-icon>
            </button>
          </mat-form-field>

          <button mat-raised-button color="primary" (click)="applyFilters()" [disabled]="loading">
            <mat-icon>filter_list</mat-icon>
            Apply Filters
          </button>
          <button mat-button (click)="clearFilters()" [disabled]="loading">
            <mat-icon>clear_all</mat-icon>
            Clear
          </button>
        </form>

        <!-- Stats -->
        <div class="stats-row">
          <div class="stat-item">
            <span class="stat-label">Total Logs:</span>
            <span class="stat-value">{{ totalLogs }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">Showing:</span>
            <span class="stat-value">{{ logs.length }}</span>
          </div>
          <div class="stat-item" *ngIf="errorCount > 0">
            <span class="stat-label">Errors:</span>
            <span class="stat-value error">{{ errorCount }}</span>
          </div>
        </div>

        <!-- Loading Spinner -->
        <div *ngIf="loading" class="loading-container">
          <mat-spinner diameter="40"></mat-spinner>
          <p>Loading logs...</p>
        </div>

        <!-- Logs Table -->
        <div *ngIf="!loading" class="table-container">
          <table mat-table [dataSource]="logs" class="logs-table">
            <!-- Level Column -->
            <ng-container matColumnDef="level">
              <th mat-header-cell *matHeaderCellDef>Level</th>
              <td mat-cell *matCellDef="let log">
                <mat-chip [style.background-color]="getLevelColor(log.level)" [style.color]="getLevelTextColor(log.level)">
                  {{ log.level }}
                </mat-chip>
              </td>
            </ng-container>

            <!-- Module Column -->
            <ng-container matColumnDef="module">
              <th mat-header-cell *matHeaderCellDef>Module</th>
              <td mat-cell *matCellDef="let log">
                <code class="module">{{ log.module }}</code>
              </td>
            </ng-container>

            <!-- Message Column -->
            <ng-container matColumnDef="message">
              <th mat-header-cell *matHeaderCellDef>Message</th>
              <td mat-cell *matCellDef="let log" class="message-cell">
                <div class="message-content" [class.error-message]="log.level === 'ERROR'">
                  {{ log.message }}
                </div>
              </td>
            </ng-container>

            <!-- Metadata Column -->
            <ng-container matColumnDef="metadata">
              <th mat-header-cell *matHeaderCellDef>Details</th>
              <td mat-cell *matCellDef="let log">
                <button
                  mat-icon-button
                  *ngIf="log.metadata"
                  (click)="viewMetadata(log)"
                  matTooltip="View metadata"
                >
                  <mat-icon>info</mat-icon>
                </button>
              </td>
            </ng-container>

            <!-- Timestamp Column -->
            <ng-container matColumnDef="createdAt">
              <th mat-header-cell *matHeaderCellDef>Timestamp</th>
              <td mat-cell *matCellDef="let log">
                <div class="timestamp">
                  {{ log.createdAt | date:'short' }}
                </div>
              </td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr
              mat-row
              *matRowDef="let row; columns: displayedColumns"
              class="log-row"
              [class.error-row]="row.level === 'ERROR'"
              [class.warn-row]="row.level === 'WARN'"
            ></tr>
          </table>

          <!-- No Data Message -->
          <div *ngIf="logs.length === 0" class="no-data">
            <mat-icon>inbox</mat-icon>
            <p>No logs found</p>
            <p class="hint">Application logs will appear here</p>
          </div>
        </div>

        <!-- Paginator -->
        <mat-paginator
          *ngIf="!loading && logs.length > 0"
          [length]="totalLogs"
          [pageSize]="pageSize"
          [pageSizeOptions]="[20, 50, 100, 200]"
          [pageIndex]="currentPage - 1"
          (page)="onPageChange($event)"
          showFirstLastButtons
        ></mat-paginator>
      </mat-card-content>
    </mat-card>
  `,
  styles: [
    `
      mat-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
      }

      mat-card-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 1.25rem;
      }

      .title-icon {
        color: #1976d2;
        font-size: 32px;
        width: 32px;
        height: 32px;
      }

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

      .filters {
        display: flex;
        gap: 16px;
        align-items: center;
        margin-bottom: 24px;
        flex-wrap: wrap;
      }

      .filter-field {
        min-width: 180px;
      }

      .filter-search {
        min-width: 300px;
      }

      .stats-row {
        display: flex;
        gap: 24px;
        margin-bottom: 16px;
        padding: 12px;
        background-color: #f5f5f5;
        border-radius: 8px;
      }

      .stat-item {
        display: flex;
        gap: 8px;
      }

      .stat-label {
        font-weight: 500;
        color: #666;
      }

      .stat-value {
        font-weight: 600;
        color: #1976d2;

        &.error {
          color: #d32f2f;
        }
      }

      .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60px 20px;
        gap: 16px;
      }

      .table-container {
        overflow-x: auto;
      }

      .logs-table {
        width: 100%;
        min-width: 900px;
      }

      .log-row {
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f5f5;
        }

        &.error-row {
          background-color: #ffebee;
        }

        &.warn-row {
          background-color: #fff3e0;
        }
      }

      .module {
        font-family: monospace;
        font-size: 0.75rem;
        background-color: #e3f2fd;
        padding: 2px 8px;
        border-radius: 4px;
        color: #1565c0;
      }

      .message-cell {
        max-width: 400px;
      }

      .message-content {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 0.875rem;

        &.error-message {
          color: #d32f2f;
          font-weight: 500;
        }
      }

      .timestamp {
        font-size: 0.75rem;
        color: #666;
        font-family: monospace;
      }

      .no-data {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60px 20px;
        color: #999;

        mat-icon {
          font-size: 64px;
          width: 64px;
          height: 64px;
          margin-bottom: 16px;
        }

        p {
          margin: 8px 0;
        }

        .hint {
          font-size: 0.875rem;
          color: #bbb;
        }
      }
    `,
  ],
})
export class LogsViewerComponent implements OnInit {
  filterForm: FormGroup;
  logs: ApplicationLog[] = [];
  displayedColumns = ['level', 'module', 'message', 'metadata', 'createdAt'];
  loading = false;
  totalLogs = 0;
  errorCount = 0;
  currentPage = 1;
  pageSize = 50;

  constructor(private fb: FormBuilder, private api: ApiService) {
    this.filterForm = this.fb.group({
      level: [''],
      module: [''],
      search: [''],
    });
  }

  ngOnInit(): void {
    this.loadLogs();
  }

  async loadLogs(): Promise<void> {
    this.loading = true;
    try {
      const params: any = {
        page: this.currentPage,
        limit: this.pageSize,
      };

      const level = this.filterForm.get('level')?.value;
      const module = this.filterForm.get('module')?.value;
      const search = this.filterForm.get('search')?.value;

      if (level) params.level = level;
      if (module) params.module = module;
      if (search) params.search = search;

      const response = await this.api
        .get<PaginatedResponse>('/admin/logs', params)
        .toPromise();

      if (response) {
        this.logs = response.data;
        this.totalLogs = response.total;
        this.errorCount = this.logs.filter(log => log.level === 'ERROR').length;
      }
    } catch (error) {
      console.error('Failed to load logs:', error);
      this.logs = [];
      this.totalLogs = 0;
      this.errorCount = 0;
    } finally {
      this.loading = false;
    }
  }

  applyFilters(): void {
    this.currentPage = 1;
    this.loadLogs();
  }

  clearFilter(field: string): void {
    this.filterForm.patchValue({ [field]: '' });
  }

  clearFilters(): void {
    this.filterForm.reset();
    this.applyFilters();
  }

  onPageChange(event: PageEvent): void {
    this.currentPage = event.pageIndex + 1;
    this.pageSize = event.pageSize;
    this.loadLogs();
  }

  viewMetadata(log: ApplicationLog): void {
    alert(`Log Metadata:\n\n${JSON.stringify(log.metadata, null, 2)}`);
  }

  exportLogs(): void {
    const dataStr = JSON.stringify(this.logs, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
    const exportFileDefaultName = `logs_${new Date().toISOString()}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  }

  getLevelColor(level: string): string {
    const colors: { [key: string]: string } = {
      INFO: '#2196f3',
      WARN: '#ff9800',
      ERROR: '#d32f2f',
    };
    return colors[level] || '#757575';
  }

  getLevelTextColor(level: string): string {
    return '#ffffff';
  }
}
