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 BlockchainEvent {
  id: string;
  eventType: string;
  contractAddress: string;
  transactionHash: string;
  blockNumber: number;
  eventData: any;
  createdAt: string;
}

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

@Component({
  selector: 'app-event-dashboard',
  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">event_note</mat-icon>
          Blockchain Events
        </mat-card-title>
        <div class="header-actions">
          <button mat-icon-button (click)="loadEvents()" [disabled]="loading" matTooltip="Refresh">
            <mat-icon>refresh</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>Event Type</mat-label>
            <mat-select formControlName="eventType" (selectionChange)="applyFilters()">
              <mat-option value="">All Types</mat-option>
              <mat-option value="LicenseRequested">License Requested</mat-option>
              <mat-option value="LicenseMinted">License Minted</mat-option>
              <mat-option value="ApprovalRecorded">Approval Recorded</mat-option>
              <mat-option value="DocumentUploaded">Document Uploaded</mat-option>
              <mat-option value="WorkflowCompleted">Workflow Completed</mat-option>
            </mat-select>
          </mat-form-field>

          <mat-form-field appearance="outline" class="filter-field">
            <mat-label>Contract Address</mat-label>
            <input matInput formControlName="contractAddress" (keyup.enter)="applyFilters()" />
            <button mat-icon-button matSuffix (click)="clearFilter('contractAddress')" *ngIf="filterForm.get('contractAddress')?.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 Events:</span>
            <span class="stat-value">{{ totalEvents }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">Showing:</span>
            <span class="stat-value">{{ events.length }}</span>
          </div>
        </div>

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

        <!-- Events Table -->
        <div *ngIf="!loading" class="table-container">
          <table mat-table [dataSource]="events" class="events-table">
            <!-- Event Type Column -->
            <ng-container matColumnDef="eventType">
              <th mat-header-cell *matHeaderCellDef>Event Type</th>
              <td mat-cell *matCellDef="let event">
                <mat-chip [style.background-color]="getEventColor(event.eventType)">
                  {{ event.eventType }}
                </mat-chip>
              </td>
            </ng-container>

            <!-- Contract Address Column -->
            <ng-container matColumnDef="contractAddress">
              <th mat-header-cell *matHeaderCellDef>Contract</th>
              <td mat-cell *matCellDef="let event">
                <code class="address">{{ event.contractAddress | slice:0:10 }}...{{ event.contractAddress | slice:-8 }}</code>
              </td>
            </ng-container>

            <!-- Transaction Hash Column -->
            <ng-container matColumnDef="transactionHash">
              <th mat-header-cell *matHeaderCellDef>Transaction</th>
              <td mat-cell *matCellDef="let event">
                <code class="address">{{ event.transactionHash | slice:0:10 }}...{{ event.transactionHash | slice:-8 }}</code>
              </td>
            </ng-container>

            <!-- Block Number Column -->
            <ng-container matColumnDef="blockNumber">
              <th mat-header-cell *matHeaderCellDef>Block</th>
              <td mat-cell *matCellDef="let event">
                <code>{{ event.blockNumber }}</code>
              </td>
            </ng-container>

            <!-- Event Data Column -->
            <ng-container matColumnDef="eventData">
              <th mat-header-cell *matHeaderCellDef>Data</th>
              <td mat-cell *matCellDef="let event">
                <button mat-icon-button (click)="viewEventData(event)" matTooltip="View decoded parameters">
                  <mat-icon>data_object</mat-icon>
                </button>
              </td>
            </ng-container>

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

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns" class="event-row"></tr>
          </table>

          <!-- No Data Message -->
          <div *ngIf="events.length === 0" class="no-data">
            <mat-icon>event_busy</mat-icon>
            <p>No blockchain events found</p>
            <p class="hint">Events will appear here as transactions occur on the blockchain</p>
          </div>
        </div>

        <!-- Paginator -->
        <mat-paginator
          *ngIf="!loading && events.length > 0"
          [length]="totalEvents"
          [pageSize]="pageSize"
          [pageSizeOptions]="[10, 20, 50, 100]"
          [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: 200px;
      }

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

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

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

      .events-table {
        width: 100%;
        min-width: 800px;
      }

      .event-row {
        cursor: pointer;
        transition: background-color 0.2s;

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

      .address {
        font-family: monospace;
        font-size: 0.75rem;
        background-color: #f5f5f5;
        padding: 2px 6px;
        border-radius: 4px;
      }

      .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 EventDashboardComponent implements OnInit {
  filterForm: FormGroup;
  events: BlockchainEvent[] = [];
  displayedColumns = ['eventType', 'contractAddress', 'transactionHash', 'blockNumber', 'eventData', 'createdAt'];
  loading = false;
  totalEvents = 0;
  currentPage = 1;
  pageSize = 20;

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

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

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

      const eventType = this.filterForm.get('eventType')?.value;
      const contractAddress = this.filterForm.get('contractAddress')?.value;

      if (eventType) params.eventType = eventType;
      if (contractAddress) params.contractAddress = contractAddress;

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

      if (response) {
        this.events = response.data;
        this.totalEvents = response.total;
      }
    } catch (error) {
      console.error('Failed to load events:', error);
      this.events = [];
      this.totalEvents = 0;
    } finally {
      this.loading = false;
    }
  }

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

  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.loadEvents();
  }

  viewEventData(event: BlockchainEvent): void {
    alert(`Event Data:\n\n${JSON.stringify(event.eventData, null, 2)}`);
  }

  getEventColor(eventType: string): string {
    const colors: { [key: string]: string } = {
      LicenseRequested: '#2196f3',
      LicenseMinted: '#4caf50',
      ApprovalRecorded: '#ff9800',
      DocumentUploaded: '#9c27b0',
      WorkflowCompleted: '#00bcd4',
    };
    return colors[eventType] || '#757575';
  }
}
