import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDialogModule, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDividerModule } from '@angular/material/divider';
import { MatChipsModule } from '@angular/material/chips';
import { Clipboard } from '@angular/cdk/clipboard';
import { BlockchainTransactionDto } from '../../../api/models';

@Component({
  selector: 'app-transaction-detail-dialog',
  standalone: true,
  imports: [
    CommonModule,
    MatDialogModule,
    MatButtonModule,
    MatIconModule,
    MatDividerModule,
    MatChipsModule,
  ],
  template: `
    <div class="dialog-container">
      <div class="dialog-header" [class]="'status-' + data.status.toLowerCase()">
        <div class="header-icon">
          <mat-icon>{{ getStatusIcon() }}</mat-icon>
        </div>
        <div class="header-text">
          <h2>Transaction Details</h2>
          <p class="subtitle">{{ formatTxType(data.type) }}</p>
        </div>
        <button mat-icon-button (click)="close()" class="close-btn">
          <mat-icon>close</mat-icon>
        </button>
      </div>

      <mat-divider></mat-divider>

      <div class="dialog-content">
        <div class="status-banner" [class]="data.status.toLowerCase()">
          <mat-icon>{{ getStatusIcon() }}</mat-icon>
          <span>{{ data.status }}</span>
        </div>

        <div class="detail-grid">
          <div class="detail-item full-width">
            <div class="detail-label">Transaction Hash</div>
            <div class="detail-value hash" (click)="copyToClipboard(data.txHash)">
              <code>{{ data.txHash }}</code>
              <mat-icon class="copy-icon">content_copy</mat-icon>
            </div>
          </div>

          <div class="detail-item">
            <div class="detail-label">Type</div>
            <div class="detail-value">
              <mat-icon class="type-icon">{{ getTxTypeIcon() }}</mat-icon>
              {{ formatTxType(data.type) }}
            </div>
          </div>

          <div class="detail-item">
            <div class="detail-label">Status</div>
            <div class="detail-value">
              <mat-chip [class]="data.status.toLowerCase()">
                {{ data.status }}
              </mat-chip>
            </div>
          </div>

          @if (data.blockNumber) {
            <div class="detail-item">
              <div class="detail-label">Block Number</div>
              <div class="detail-value highlight">{{ data.blockNumber | number }}</div>
            </div>
          }

          <div class="detail-item">
            <div class="detail-label">Timestamp</div>
            <div class="detail-value">{{ data.timestamp | date:'medium' }}</div>
          </div>

          @if (data.gasUsed) {
            <div class="detail-item">
              <div class="detail-label">Gas Used</div>
              <div class="detail-value">{{ data.gasUsed | number }}</div>
            </div>
          }

          @if (data.data && hasDataKeys()) {
            <div class="detail-item full-width">
              <div class="detail-label">Additional Data</div>
              <div class="detail-value">
                <pre class="data-json">{{ data.data | json }}</pre>
              </div>
            </div>
          }
        </div>
      </div>

      <mat-divider></mat-divider>

      <div class="dialog-actions">
        <button mat-button (click)="close()">Close</button>
        <button mat-flat-button color="primary" (click)="copyAllDetails()">
          <mat-icon>content_copy</mat-icon>
          Copy Details
        </button>
      </div>
    </div>
  `,
  styles: [`
    .dialog-container {
      display: flex;
      flex-direction: column;
    }

    .dialog-header {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 20px 24px;
      color: white;

      &.status-confirmed {
        background: linear-gradient(135deg, #198754 0%, #28a745 100%);
      }

      &.status-pending {
        background: linear-gradient(135deg, #1D0A69 0%, #2563EB 100%);
      }

      &.status-failed {
        background: linear-gradient(135deg, #DC3545 0%, #e74c3c 100%);
      }
    }

    .header-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;

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

    .header-text {
      flex: 1;

      h2 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
      }

      .subtitle {
        margin: 4px 0 0;
        font-size: 0.85rem;
        opacity: 0.9;
      }
    }

    .close-btn {
      color: white;
    }

    .dialog-content {
      padding: 24px;
      max-height: 60vh;
      overflow-y: auto;
    }

    .status-banner {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px;
      border-radius: 8px;
      margin-bottom: 24px;
      font-weight: 600;

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

      &.confirmed {
        background: rgba(25, 135, 84, 0.1);
        color: #198754;
      }

      &.pending {
        background: rgba(37, 99, 235, 0.1);
        color: #2563EB;
      }

      &.failed {
        background: rgba(220, 53, 69, 0.1);
        color: #DC3545;
      }
    }

    .detail-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
    }

    .detail-item {
      &.full-width {
        grid-column: 1 / -1;
      }
    }

    .detail-label {
      font-size: 0.75rem;
      color: #6b7280;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 6px;
      font-weight: 500;
    }

    .detail-value {
      font-size: 0.95rem;
      color: #1f2937;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 8px;

      &.highlight {
        color: #2563EB;
        font-size: 1.125rem;
        font-weight: 700;
      }

      &.hash {
        cursor: pointer;
        padding: 8px 12px;
        background: #f5f5f5;
        border-radius: 8px;
        transition: background 0.2s;

        &:hover {
          background: #eee;
        }

        code {
          font-family: 'Monaco', 'Consolas', monospace;
          font-size: 0.8rem;
          word-break: break-all;
          flex: 1;
          color: #1f2937;
        }

        .copy-icon {
          font-size: 16px;
          width: 16px;
          height: 16px;
          color: #6b7280;
        }
      }

      &.link {
        color: #2563EB;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      .type-icon {
        font-size: 18px;
        width: 18px;
        height: 18px;
        color: #1D0A69;
      }

      mat-chip {
        font-size: 0.75rem;

        &.confirmed {
          background: rgba(25, 135, 84, 0.1) !important;
          color: #198754 !important;
        }

        &.pending {
          background: rgba(37, 99, 235, 0.1) !important;
          color: #2563EB !important;
        }

        &.failed {
          background: rgba(220, 53, 69, 0.1) !important;
          color: #DC3545 !important;
        }
      }
    }

    .dialog-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      padding: 16px 24px;
      background: #fafafa;

      button mat-icon {
        margin-right: 4px;
        font-size: 18px;
        width: 18px;
        height: 18px;
      }
    }

    .data-json {
      font-family: 'Monaco', 'Consolas', monospace;
      font-size: 0.8rem;
      background: #f5f5f5;
      color: #1f2937;
      padding: 12px;
      border-radius: 8px;
      overflow-x: auto;
      margin: 0;
      white-space: pre-wrap;
      word-break: break-word;
    }
  `],
})
export class TransactionDetailDialogComponent {
  readonly data = inject<BlockchainTransactionDto>(MAT_DIALOG_DATA);
  private readonly dialogRef = inject(MatDialogRef<TransactionDetailDialogComponent>);
  private readonly clipboard = inject(Clipboard);

  close(): void {
    this.dialogRef.close();
  }

  copyToClipboard(text: string): void {
    this.clipboard.copy(text);
  }

  copyAllDetails(): void {
    const details = `Transaction Hash: ${this.data.txHash}
Type: ${this.formatTxType(this.data.type)}
Status: ${this.data.status}
Block Number: ${this.data.blockNumber || 'Pending'}
Timestamp: ${this.data.timestamp}
${this.data.gasUsed ? `Gas Used: ${this.data.gasUsed}` : ''}`;

    this.clipboard.copy(details);
  }

  hasDataKeys(): boolean {
    return this.data.data && Object.keys(this.data.data).length > 0;
  }

  getStatusIcon(): string {
    switch (this.data.status) {
      case 'CONFIRMED': return 'check_circle';
      case 'PENDING': return 'schedule';
      case 'FAILED': return 'error';
      default: return 'receipt_long';
    }
  }

  getTxTypeIcon(): string {
    const icons: Record<string, string> = {
      LICENSE_MINT: 'verified',
      DOCUMENT_HASH: 'fingerprint',
      APPROVAL_RECORD: 'approval',
      LICENSE_TRANSFER: 'swap_horiz',
      REVOCATION: 'block',
    };
    return icons[this.data.type] || 'receipt_long';
  }

  formatTxType(type: string): string {
    if (!type) return 'Blockchain Transaction';
    const typeMap: Record<string, string> = {
      'LICENSE_MINT': 'License Minting',
      'DOCUMENT_HASH': 'Document Hash',
      'APPROVAL_RECORD': 'Approval Record',
      'LICENSE_TRANSFER': 'License Transfer',
      'REVOCATION': 'License Revocation',
      'TRANSACTION': 'Blockchain Transaction',
    };
    return typeMap[type] || type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
  }
}
