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 { 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 { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { ApiService } from '../../../core/services/api.service';
import { TransactionDetailDialogComponent } from '../../../shared/components/blockchain-explorer-mini/transaction-detail-dialog.component';

interface BlockchainTransaction {
  id: string;
  transactionHash: string;
  from: string;
  to: string;
  value: string;
  gasUsed: string;
  gasPrice: string;
  status: 'PENDING' | 'CONFIRMED' | 'FAILED';
  blockNumber?: number;
  requestId?: string;
  approvalId?: string;
  createdAt: string;
}

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

@Component({
  selector: 'app-transaction-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatCardModule,
    MatTableModule,
    MatPaginatorModule,
    MatFormFieldModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    MatDialogModule,
  ],
  template: `
    <mat-card>
      <mat-card-header>
        <mat-card-title>
          <mat-icon class="title-icon">receipt_long</mat-icon>
          Blockchain Transactions
        </mat-card-title>
        <div class="header-actions">
          <button mat-icon-button (click)="loadTransactions()" [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>Status</mat-label>
            <mat-select formControlName="status" (selectionChange)="applyFilters()">
              <mat-option value="">All Statuses</mat-option>
              <mat-option value="PENDING">Pending</mat-option>
              <mat-option value="CONFIRMED">Confirmed</mat-option>
              <mat-option value="FAILED">Failed</mat-option>
            </mat-select>
          </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-grid">
          <div class="stat-card confirmed">
            <mat-icon>check_circle</mat-icon>
            <div class="stat-content">
              <div class="stat-value">{{ confirmedCount }}</div>
              <div class="stat-label">Confirmed</div>
            </div>
          </div>
          <div class="stat-card pending">
            <mat-icon>pending</mat-icon>
            <div class="stat-content">
              <div class="stat-value">{{ pendingCount }}</div>
              <div class="stat-label">Pending</div>
            </div>
          </div>
          <div class="stat-card failed" *ngIf="failedCount > 0">
            <mat-icon>error</mat-icon>
            <div class="stat-content">
              <div class="stat-value">{{ failedCount }}</div>
              <div class="stat-label">Failed</div>
            </div>
          </div>
          <div class="stat-card total">
            <mat-icon>receipt_long</mat-icon>
            <div class="stat-content">
              <div class="stat-value">{{ totalTransactions }}</div>
              <div class="stat-label">Total</div>
            </div>
          </div>
        </div>

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

        <!-- Transactions Table -->
        <div *ngIf="!loading" class="table-container">
          <table mat-table [dataSource]="transactions" class="transactions-table">
            <!-- Transaction Hash Column -->
            <ng-container matColumnDef="transactionHash">
              <th mat-header-cell *matHeaderCellDef>Transaction Hash</th>
              <td mat-cell *matCellDef="let tx">
                <code class="hash">{{ tx.transactionHash | slice:0:16 }}...{{ tx.transactionHash | slice:-12 }}</code>
              </td>
            </ng-container>

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

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

            <!-- Status Column -->
            <ng-container matColumnDef="status">
              <th mat-header-cell *matHeaderCellDef>Status</th>
              <td mat-cell *matCellDef="let tx">
                <mat-chip [style.background-color]="getStatusColor(tx.status)" style="color: white;">
                  {{ tx.status }}
                </mat-chip>
              </td>
            </ng-container>

            <!-- Block Number Column -->
            <ng-container matColumnDef="blockNumber">
              <th mat-header-cell *matHeaderCellDef>Block</th>
              <td mat-cell *matCellDef="let tx">
                <code *ngIf="tx.blockNumber">{{ tx.blockNumber }}</code>
                <span *ngIf="!tx.blockNumber" class="pending-text">-</span>
              </td>
            </ng-container>

            <!-- Gas Used Column -->
            <ng-container matColumnDef="gasUsed">
              <th mat-header-cell *matHeaderCellDef>Gas Used</th>
              <td mat-cell *matCellDef="let tx">
                <code class="gas">{{ tx.gasUsed || '0' }}</code>
              </td>
            </ng-container>

            <!-- Linked To Column -->
            <ng-container matColumnDef="linkedTo">
              <th mat-header-cell *matHeaderCellDef>Linked To</th>
              <td mat-cell *matCellDef="let tx">
                <div *ngIf="tx.requestId" class="link-chip">
                  <mat-icon>description</mat-icon>
                  Request
                </div>
                <div *ngIf="tx.approvalId" class="link-chip">
                  <mat-icon>approval</mat-icon>
                  Approval
                </div>
                <span *ngIf="!tx.requestId && !tx.approvalId" class="no-link">-</span>
              </td>
            </ng-container>

            <!-- Actions Column -->
            <ng-container matColumnDef="actions">
              <th mat-header-cell *matHeaderCellDef>Actions</th>
              <td mat-cell *matCellDef="let tx">
                <button mat-icon-button (click)="viewTransactionDetails(tx)" matTooltip="View details">
                  <mat-icon>visibility</mat-icon>
                </button>
              </td>
            </ng-container>

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

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

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

        <!-- Paginator -->
        <mat-paginator
          *ngIf="!loading && transactions.length > 0"
          [length]="totalTransactions"
          [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-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
      }

      .stat-card {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 20px;
        border-radius: 12px;
        color: white;

        &.confirmed { background: linear-gradient(135deg, #059669 0%, #10b981 100%); }
        &.pending { background: linear-gradient(135deg, #1D0A69 0%, #2563EB 100%); }
        &.failed { background: linear-gradient(135deg, #DC3545 0%, #e74c3c 100%); }
        &.total { background: linear-gradient(135deg, #8B5CF6 0%, #6366F1 100%); }

        mat-icon {
          font-size: 40px;
          width: 40px;
          height: 40px;
          color: white;
        }
      }

      .stat-content {
        flex: 1;
      }

      .stat-value {
        font-size: 2rem;
        font-weight: 600;
        color: white;
      }

      .stat-label {
        font-size: 0.875rem;
        color: rgba(255, 255, 255, 0.9);
      }

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

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

      .transactions-table {
        width: 100%;
        min-width: 1000px;
      }

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

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

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

      .gas {
        font-family: monospace;
        font-size: 0.75rem;
      }

      .pending-text {
        color: #999;
      }

      .link-chip {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        background-color: #e3f2fd;
        border-radius: 4px;
        font-size: 0.75rem;
        color: #1565c0;

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

      .no-link {
        color: #999;
      }

      .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 TransactionDashboardComponent implements OnInit {
  filterForm: FormGroup;
  transactions: BlockchainTransaction[] = [];
  displayedColumns = ['transactionHash', 'from', 'to', 'status', 'blockNumber', 'gasUsed', 'linkedTo', 'actions', 'createdAt'];
  loading = false;
  totalTransactions = 0;
  confirmedCount = 0;
  pendingCount = 0;
  failedCount = 0;
  currentPage = 1;
  pageSize = 20;

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

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

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

      const status = this.filterForm.get('status')?.value;
      if (status) params.status = status;

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

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

  updateCounts(): void {
    this.confirmedCount = this.transactions.filter(tx => tx.status === 'CONFIRMED').length;
    this.pendingCount = this.transactions.filter(tx => tx.status === 'PENDING').length;
    this.failedCount = this.transactions.filter(tx => tx.status === 'FAILED').length;
  }

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

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

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

  viewTransactionDetails(tx: BlockchainTransaction): void {
    // Convert to BlockchainTransactionDto format for the dialog
    const dialogData = {
      id: tx.id,
      txHash: tx.transactionHash || (tx as any).txHash,
      type: (tx as any).txType || 'TRANSACTION',
      status: tx.status,
      gasUsed: tx.gasUsed ? parseInt(tx.gasUsed, 10) : undefined,
      blockNumber: tx.blockNumber,
      timestamp: tx.createdAt,
      data: {
        from: tx.from || (tx as any).fromAddress,
        to: tx.to || (tx as any).toAddress,
        value: tx.value,
        requestId: tx.requestId || (tx as any).relatedEntityId,
      },
    };

    this.dialog.open(TransactionDetailDialogComponent, {
      data: dialogData,
      width: '600px',
      maxHeight: '90vh',
      panelClass: 'blockchain-detail-dialog',
    });
  }

  getStatusColor(status: string): string {
    const colors: { [key: string]: string } = {
      CONFIRMED: '#4caf50',
      PENDING: '#2196f3',
      FAILED: '#f44336',
    };
    return colors[status] || '#757575';
  }
}
