import { Component, OnInit, OnDestroy, inject, signal, computed, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatChipsModule } from '@angular/material/chips';
import { MatRippleModule } from '@angular/material/core';
import { StatusBadgeComponent } from '../../../shared/components/status-badge/status-badge.component';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ApprovalResponseDto } from '../../../api/models';

interface WalletInfo {
  address: string;
  balance: string;
  balanceUsd: string;
  transactionCount: number;
  lastActive: string;
}

interface Transaction {
  hash: string;
  type: 'APPROVAL' | 'REJECTION' | 'MINT_NFT';
  status: 'confirmed' | 'pending' | 'failed';
  timestamp: Date;
  requestId?: string;
}

@Component({
  selector: 'app-department-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    MatChipsModule,
    MatRippleModule,
    StatusBadgeComponent,
  ],
  template: `
    <div class="dashboard-container">
      <!-- Header Section -->
      <header class="dashboard-header">
        <div class="header-content">
          <div class="welcome-section">
            <h1 class="welcome-title">
              Welcome back, <span class="highlight">{{ departmentName() }}</span>
            </h1>
            <p class="welcome-subtitle">
              You have <strong>{{ pendingCount() }}</strong> pending approvals requiring your attention
            </p>
          </div>
          <div class="header-actions">
            <button mat-flat-button color="primary" routerLink="/approvals" class="primary-action">
              <mat-icon>pending_actions</mat-icon>
              Review Pending
            </button>
          </div>
        </div>
      </header>

      <!-- Main Grid -->
      <div class="dashboard-grid">
        <!-- Left Column - Stats & Approvals -->
        <div class="left-column">
          <!-- Stats Cards -->
          <section class="stats-section">
            <div class="stats-grid">
              @for (stat of stats(); track stat.label) {
                <div class="stat-card" [class]="'stat-' + stat.type">
                  <div class="stat-icon-wrapper" [class]="stat.type">
                    <mat-icon>{{ stat.icon }}</mat-icon>
                  </div>
                  <div class="stat-content">
                    <span class="stat-value">{{ stat.value }}</span>
                    <span class="stat-label">{{ stat.label }}</span>
                  </div>
                  @if (stat.change) {
                    <div class="stat-change" [class.positive]="stat.change > 0" [class.negative]="stat.change < 0">
                      <mat-icon>{{ stat.change > 0 ? 'trending_up' : 'trending_down' }}</mat-icon>
                      {{ stat.change > 0 ? '+' : '' }}{{ stat.change }}%
                    </div>
                  }
                </div>
              }
            </div>
          </section>

          <!-- Pending Approvals -->
          <section class="approvals-section">
            <div class="section-header">
              <div class="section-title">
                <mat-icon>pending_actions</mat-icon>
                <h2>Pending Approvals</h2>
                @if (pendingCount() > 0) {
                  <span class="badge pulse">{{ pendingCount() }}</span>
                }
              </div>
              <button mat-button routerLink="/approvals">
                View All
                <mat-icon>arrow_forward</mat-icon>
              </button>
            </div>

            @if (loading()) {
              <div class="loading-state">
                <div class="skeleton-list">
                  @for (i of [1, 2, 3]; track i) {
                    <div class="skeleton-item">
                      <div class="skeleton skeleton-avatar"></div>
                      <div class="skeleton-content">
                        <div class="skeleton skeleton-title"></div>
                        <div class="skeleton skeleton-subtitle"></div>
                      </div>
                    </div>
                  }
                </div>
              </div>
            } @else if (pendingApprovals().length === 0) {
              <div class="empty-approvals">
                <div class="empty-icon success">
                  <mat-icon>check_circle</mat-icon>
                </div>
                <h3>All caught up!</h3>
                <p>No pending approvals at the moment</p>
              </div>
            } @else {
              <div class="approvals-list">
                @for (approval of pendingApprovals().slice(0, 5); track approval.id) {
                  <a class="approval-card" [routerLink]="['/requests', approval.requestId]" matRipple>
                    <div class="approval-avatar">
                      <mat-icon>description</mat-icon>
                    </div>
                    <div class="approval-content">
                      <div class="approval-title">Request #{{ approval.requestId.slice(0, 8).toUpperCase() }}</div>
                      <div class="approval-meta">
                        <span class="meta-item">
                          <mat-icon>calendar_today</mat-icon>
                          {{ approval.createdAt | date: 'MMM d, y' }}
                        </span>
                      </div>
                    </div>
                    <div class="approval-status">
                      <app-status-badge [status]="approval.status" />
                      <mat-icon class="arrow-icon">chevron_right</mat-icon>
                    </div>
                  </a>
                }
              </div>
            }
          </section>
        </div>

        <!-- Right Column - Wallet -->
        <div class="right-column">
          <!-- Department Wallet Card -->
          <section class="wallet-section">
            <div class="wallet-card">
              <div class="wallet-gradient-bg"></div>
              <div class="wallet-content">
                <div class="wallet-header">
                  <div class="wallet-title">
                    <span class="wallet-label">Department Wallet</span>
                    <span class="wallet-name">{{ departmentName() }}</span>
                  </div>
                  <div class="wallet-icon">
                    <mat-icon>account_balance_wallet</mat-icon>
                  </div>
                </div>

                <div class="wallet-balance">
                  <span class="balance-label">Available Balance</span>
                  <div class="balance-value">
                    <span class="balance-amount">{{ wallet().balance }}</span>
                    <span class="balance-currency">ETH</span>
                  </div>
                  <span class="balance-usd">≈ {{ wallet().balanceUsd }} USD</span>
                </div>

                <div class="wallet-address" (click)="copyAddress()">
                  <div class="address-content">
                    <mat-icon class="address-icon">link</mat-icon>
                    <span class="address-text">{{ formatAddress(wallet().address) }}</span>
                  </div>
                  <button mat-icon-button class="copy-btn" matTooltip="Copy address">
                    <mat-icon>{{ copied() ? 'check' : 'content_copy' }}</mat-icon>
                  </button>
                </div>

                <div class="wallet-stats">
                  <div class="wallet-stat">
                    <span class="stat-value">{{ wallet().transactionCount }}</span>
                    <span class="stat-label">Transactions</span>
                  </div>
                  <div class="wallet-stat">
                    <span class="stat-value">{{ wallet().lastActive }}</span>
                    <span class="stat-label">Last Active</span>
                  </div>
                </div>
              </div>
            </div>
          </section>

          <!-- Recent Transactions -->
          <section class="transactions-section">
            <div class="section-header">
              <div class="section-title">
                <mat-icon>receipt_long</mat-icon>
                <h2>Recent Transactions</h2>
              </div>
              <button mat-button>
                View All
                <mat-icon>arrow_forward</mat-icon>
              </button>
            </div>

            <div class="transactions-list">
              @for (tx of recentTransactions(); track tx.hash) {
                <div class="transaction-item" [class]="'tx-' + tx.status">
                  <div class="tx-icon" [class]="tx.type.toLowerCase()">
                    <mat-icon>
                      {{ tx.type === 'APPROVAL' ? 'check_circle' : tx.type === 'REJECTION' ? 'cancel' : 'token' }}
                    </mat-icon>
                  </div>
                  <div class="tx-content">
                    <div class="tx-title">
                      {{ tx.type === 'APPROVAL' ? 'Approval Transaction' : tx.type === 'REJECTION' ? 'Rejection Transaction' : 'NFT Minting' }}
                    </div>
                    <div class="tx-hash" (click)="copyHash(tx.hash)">
                      <span class="hash-text">{{ formatHash(tx.hash) }}</span>
                      <mat-icon class="copy-icon">content_copy</mat-icon>
                    </div>
                  </div>
                  <div class="tx-meta">
                    <span class="tx-status" [class]="tx.status">
                      <span class="status-dot"></span>
                      {{ tx.status }}
                    </span>
                    <span class="tx-time">{{ tx.timestamp | date: 'shortTime' }}</span>
                  </div>
                </div>
              }
            </div>
          </section>

          <!-- Blockchain Status -->
          <section class="blockchain-section">
            <div class="blockchain-card">
              <div class="blockchain-header">
                <mat-icon>hub</mat-icon>
                <span>Hyperledger Besu Network</span>
              </div>
              <div class="blockchain-stats">
                <div class="bc-stat">
                  <span class="bc-value">{{ blockHeight() }}</span>
                  <span class="bc-label">Block Height</span>
                </div>
                <div class="bc-stat">
                  <span class="bc-value">{{ totalTxCount() }}</span>
                  <span class="bc-label">Total Txs</span>
                </div>
                <div class="bc-stat">
                  <span class="bc-value">4</span>
                  <span class="bc-label">Nodes</span>
                </div>
              </div>
              <div class="blockchain-status">
                <span class="status-indicator online"></span>
                <span class="status-text">Network Healthy</span>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  `,
  styles: [`
    // =============================================================================
    // DEPARTMENT DASHBOARD - World-Class Crypto/Government UI
    // =============================================================================

    .dashboard-container {
      max-width: 1400px;
      margin: 0 auto;
      animation: fadeIn 0.3s ease-out;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    // =============================================================================
    // HEADER
    // =============================================================================
    .dashboard-header {
      margin-bottom: 32px;
    }

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      flex-wrap: wrap;
      gap: 16px;
    }

    .welcome-title {
      font-size: 28px;
      font-weight: 700;
      color: var(--dbim-brown);
      margin: 0 0 8px;

      .highlight {
        color: var(--dbim-blue-dark);
      }
    }

    .welcome-subtitle {
      font-size: 15px;
      color: var(--dbim-grey-2);
      margin: 0;

      strong {
        color: var(--dbim-error);
        font-weight: 600;
      }
    }

    .primary-action {
      padding: 12px 24px;
      font-size: 14px;
      font-weight: 500;
      border-radius: 12px;
      background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--crypto-indigo) 100%);

      mat-icon {
        margin-right: 8px;
      }
    }

    // =============================================================================
    // MAIN GRID
    // =============================================================================
    .dashboard-grid {
      display: grid;
      grid-template-columns: 1fr 400px;
      gap: 24px;

      @media (max-width: 1200px) {
        grid-template-columns: 1fr;
      }
    }

    // =============================================================================
    // STATS SECTION
    // =============================================================================
    .stats-section {
      margin-bottom: 24px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;

      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }
    }

    .stat-card {
      background: var(--dbim-white);
      border-radius: 16px;
      padding: 20px;
      display: flex;
      align-items: flex-start;
      gap: 16px;
      box-shadow: var(--shadow-card);
      border: 1px solid rgba(29, 10, 105, 0.06);
      transition: all 0.2s ease;

      &:hover {
        box-shadow: var(--shadow-card-hover);
        transform: translateY(-2px);
      }
    }

    .stat-icon-wrapper {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

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

      &.pending {
        background: rgba(255, 193, 7, 0.15);
        color: #B8860B;
      }

      &.approved {
        background: rgba(25, 135, 84, 0.1);
        color: var(--dbim-success);
      }

      &.rejected {
        background: rgba(220, 53, 69, 0.1);
        color: var(--dbim-error);
      }
    }

    .stat-content {
      flex: 1;
      min-width: 0;
    }

    .stat-value {
      display: block;
      font-size: 28px;
      font-weight: 700;
      color: var(--dbim-brown);
      line-height: 1.2;
    }

    .stat-label {
      display: block;
      font-size: 13px;
      color: var(--dbim-grey-2);
      margin-top: 4px;
    }

    .stat-change {
      display: flex;
      align-items: center;
      gap: 2px;
      font-size: 12px;
      font-weight: 500;
      padding: 4px 8px;
      border-radius: 6px;

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

      &.positive {
        background: rgba(25, 135, 84, 0.1);
        color: var(--dbim-success);
      }

      &.negative {
        background: rgba(220, 53, 69, 0.1);
        color: var(--dbim-error);
      }
    }

    // =============================================================================
    // SECTIONS
    // =============================================================================
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;

      mat-icon {
        color: var(--dbim-grey-2);
        font-size: 20px;
        width: 20px;
        height: 20px;
      }

      h2 {
        font-size: 18px;
        font-weight: 600;
        color: var(--dbim-brown);
        margin: 0;
      }

      .badge {
        min-width: 20px;
        height: 20px;
        padding: 0 6px;
        border-radius: 10px;
        background: var(--dbim-error);
        color: white;
        font-size: 11px;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;

        &.pulse {
          animation: pulse 2s infinite;
        }
      }
    }

    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.6; }
    }

    // =============================================================================
    // APPROVALS SECTION
    // =============================================================================
    .approvals-section {
      background: var(--dbim-white);
      border-radius: 16px;
      padding: 24px;
      box-shadow: var(--shadow-card);
      border: 1px solid rgba(29, 10, 105, 0.06);
    }

    .loading-state {
      padding: 16px 0;
    }

    .skeleton-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .skeleton-item {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px;
      background: var(--dbim-linen);
      border-radius: 12px;
    }

    .skeleton {
      background: linear-gradient(90deg, #f0f0f0 25%, #e8e8e8 50%, #f0f0f0 75%);
      background-size: 200% 100%;
      animation: shimmer 1.5s infinite;
      border-radius: 6px;
    }

    @keyframes shimmer {
      0% { background-position: 200% 0; }
      100% { background-position: -200% 0; }
    }

    .skeleton-avatar {
      width: 44px;
      height: 44px;
      border-radius: 10px;
      flex-shrink: 0;
    }

    .skeleton-content {
      flex: 1;
    }

    .skeleton-title {
      height: 16px;
      width: 60%;
      margin-bottom: 8px;
    }

    .skeleton-subtitle {
      height: 12px;
      width: 40%;
    }

    .empty-approvals {
      text-align: center;
      padding: 48px 24px;

      .empty-icon {
        width: 64px;
        height: 64px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;

        &.success {
          background: rgba(25, 135, 84, 0.1);
          color: var(--dbim-success);
        }

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

      h3 {
        font-size: 18px;
        font-weight: 600;
        color: var(--dbim-brown);
        margin: 0 0 8px;
      }

      p {
        font-size: 14px;
        color: var(--dbim-grey-2);
        margin: 0;
      }
    }

    .approvals-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .approval-card {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px;
      background: var(--dbim-linen);
      border-radius: 12px;
      text-decoration: none;
      color: inherit;
      transition: all 0.15s ease;
      cursor: pointer;

      &:hover {
        background: var(--dbim-blue-subtle);
        transform: translateX(4px);

        .arrow-icon {
          transform: translateX(4px);
        }
      }
    }

    .approval-avatar {
      width: 44px;
      height: 44px;
      border-radius: 10px;
      background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--crypto-indigo) 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

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

    .approval-content {
      flex: 1;
      min-width: 0;
    }

    .approval-title {
      font-size: 14px;
      font-weight: 600;
      color: var(--dbim-brown);
      margin-bottom: 4px;
    }

    .approval-meta {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .meta-item {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 12px;
      color: var(--dbim-grey-2);

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

    .approval-status {
      display: flex;
      align-items: center;
      gap: 8px;

      .arrow-icon {
        color: var(--dbim-grey-2);
        transition: transform 0.15s ease;
      }
    }

    // =============================================================================
    // WALLET SECTION
    // =============================================================================
    .wallet-section {
      margin-bottom: 24px;
    }

    .wallet-card {
      position: relative;
      border-radius: 20px;
      overflow: hidden;
      box-shadow: var(--shadow-elevated);
    }

    .wallet-gradient-bg {
      position: absolute;
      inset: 0;
      background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--crypto-indigo) 50%, var(--crypto-purple) 100%);

      &::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
      }

      &::after {
        content: '';
        position: absolute;
        bottom: -30%;
        left: -30%;
        width: 60%;
        height: 60%;
        background: radial-gradient(circle, rgba(99, 102, 241, 0.3) 0%, transparent 60%);
      }
    }

    .wallet-content {
      position: relative;
      padding: 24px;
      color: white;
      z-index: 1;
    }

    .wallet-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24px;
    }

    .wallet-label {
      display: block;
      font-size: 12px;
      opacity: 0.7;
      margin-bottom: 4px;
    }

    .wallet-name {
      display: block;
      font-size: 16px;
      font-weight: 600;
    }

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

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

    .wallet-balance {
      margin-bottom: 24px;
    }

    .balance-label {
      display: block;
      font-size: 12px;
      opacity: 0.7;
      margin-bottom: 4px;
    }

    .balance-value {
      display: flex;
      align-items: baseline;
      gap: 8px;
    }

    .balance-amount {
      font-size: 36px;
      font-weight: 700;
      letter-spacing: -0.02em;
    }

    .balance-currency {
      font-size: 18px;
      font-weight: 500;
      opacity: 0.8;
    }

    .balance-usd {
      display: block;
      font-size: 14px;
      opacity: 0.7;
      margin-top: 4px;
    }

    .wallet-address {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12px;
      margin-bottom: 20px;
      cursor: pointer;
      transition: background 0.15s ease;

      &:hover {
        background: rgba(255, 255, 255, 0.15);
      }
    }

    .address-content {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .address-icon {
      font-size: 16px;
      width: 16px;
      height: 16px;
      opacity: 0.7;
    }

    .address-text {
      font-family: 'Roboto Mono', monospace;
      font-size: 13px;
    }

    .copy-btn {
      color: white;
      opacity: 0.7;

      &:hover {
        opacity: 1;
      }

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

    .wallet-stats {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
    }

    .wallet-stat {
      text-align: center;
      padding: 12px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 10px;

      .stat-value {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: white;
      }

      .stat-label {
        display: block;
        font-size: 11px;
        opacity: 0.7;
        margin-top: 2px;
      }
    }

    // =============================================================================
    // TRANSACTIONS SECTION
    // =============================================================================
    .transactions-section {
      background: var(--dbim-white);
      border-radius: 16px;
      padding: 20px;
      box-shadow: var(--shadow-card);
      border: 1px solid rgba(29, 10, 105, 0.06);
      margin-bottom: 24px;
    }

    .transactions-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .transaction-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      background: var(--dbim-linen);
      border-radius: 10px;
      transition: all 0.15s ease;

      &:hover {
        background: #e5e5e5;
      }
    }

    .tx-icon {
      width: 36px;
      height: 36px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

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

      &.approval {
        background: rgba(25, 135, 84, 0.1);
        color: var(--dbim-success);
      }

      &.rejection {
        background: rgba(220, 53, 69, 0.1);
        color: var(--dbim-error);
      }

      &.mint_nft {
        background: rgba(139, 92, 246, 0.1);
        color: var(--crypto-purple);
      }
    }

    .tx-content {
      flex: 1;
      min-width: 0;
    }

    .tx-title {
      font-size: 13px;
      font-weight: 500;
      color: var(--dbim-brown);
      margin-bottom: 2px;
    }

    .tx-hash {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      font-family: 'Roboto Mono', monospace;
      font-size: 11px;
      color: var(--dbim-grey-2);
      cursor: pointer;

      &:hover {
        color: var(--dbim-info);
      }

      .copy-icon {
        font-size: 12px;
        width: 12px;
        height: 12px;
        opacity: 0;
        transition: opacity 0.15s ease;
      }

      &:hover .copy-icon {
        opacity: 1;
      }
    }

    .tx-meta {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 4px;
    }

    .tx-status {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 11px;
      font-weight: 500;
      text-transform: capitalize;

      .status-dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
      }

      &.confirmed {
        color: var(--dbim-success);
        .status-dot { background: var(--dbim-success); }
      }

      &.pending {
        color: #B8860B;
        .status-dot { background: var(--dbim-warning); }
      }

      &.failed {
        color: var(--dbim-error);
        .status-dot { background: var(--dbim-error); }
      }
    }

    .tx-time {
      font-size: 11px;
      color: var(--dbim-grey-2);
    }

    // =============================================================================
    // BLOCKCHAIN SECTION
    // =============================================================================
    .blockchain-section {
      margin-bottom: 24px;
    }

    .blockchain-card {
      background: var(--dbim-white);
      border-radius: 16px;
      padding: 20px;
      box-shadow: var(--shadow-card);
      border: 1px solid rgba(29, 10, 105, 0.06);
    }

    .blockchain-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;

      mat-icon {
        color: var(--crypto-indigo);
      }

      span {
        font-size: 14px;
        font-weight: 600;
        color: var(--dbim-brown);
      }
    }

    .blockchain-stats {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-bottom: 16px;
    }

    .bc-stat {
      text-align: center;
      padding: 12px;
      background: var(--dbim-linen);
      border-radius: 10px;

      .bc-value {
        display: block;
        font-size: 16px;
        font-weight: 700;
        color: var(--dbim-brown);
      }

      .bc-label {
        display: block;
        font-size: 10px;
        color: var(--dbim-grey-2);
        margin-top: 2px;
        text-transform: uppercase;
        letter-spacing: 0.02em;
      }
    }

    .blockchain-status {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 10px;
      background: rgba(25, 135, 84, 0.1);
      border-radius: 8px;

      .status-indicator {
        width: 8px;
        height: 8px;
        border-radius: 50%;

        &.online {
          background: var(--dbim-success);
          box-shadow: 0 0 8px var(--dbim-success);
          animation: pulse 2s infinite;
        }
      }

      .status-text {
        font-size: 12px;
        font-weight: 500;
        color: var(--dbim-success);
      }
    }

    // =============================================================================
    // RESPONSIVE
    // =============================================================================
    @media (max-width: 768px) {
      .welcome-title {
        font-size: 22px;
      }

      .stats-grid {
        grid-template-columns: 1fr 1fr;
      }

      .stat-card {
        padding: 16px;
      }

      .stat-value {
        font-size: 22px;
      }

      .balance-amount {
        font-size: 28px;
      }
    }
  `],
})
export class DepartmentDashboardComponent implements OnInit, OnDestroy {
  private readonly api = inject(ApiService);
  private readonly authService = inject(AuthService);
  private readonly notification = inject(NotificationService);
  private readonly destroyRef = inject(DestroyRef);

  private copyTimeoutId: ReturnType<typeof setTimeout> | null = null;

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly copied = signal(false);
  readonly pendingApprovals = signal<ApprovalResponseDto[]>([]);
  readonly pendingCount = signal(0);
  readonly approvedCount = signal(12);
  readonly rejectedCount = signal(3);

  readonly departmentName = computed(() => {
    const user = this.authService.getCurrentUser();
    return user?.name || 'Department';
  });

  // Mock wallet data - TODO: Replace with real API
  readonly wallet = signal<WalletInfo>({
    address: '0x742d35Cc6634C0532925a3b844Bc9e7595f8F843',
    balance: '0.0847',
    balanceUsd: '$215.42',
    transactionCount: 47,
    lastActive: '2h ago',
  });

  // Mock transactions - TODO: Replace with real API
  readonly recentTransactions = signal<Transaction[]>([
    {
      hash: '0x8f3e4a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f',
      type: 'APPROVAL',
      status: 'confirmed',
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
    },
    {
      hash: '0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b',
      type: 'APPROVAL',
      status: 'confirmed',
      timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000),
    },
    {
      hash: '0x9f8e7d6c5b4a3c2d1e0f9a8b7c6d5e4f3a2b1c0d',
      type: 'REJECTION',
      status: 'confirmed',
      timestamp: new Date(Date.now() - 48 * 60 * 60 * 1000),
    },
    {
      hash: '0x5e4d3c2b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d',
      type: 'MINT_NFT',
      status: 'pending',
      timestamp: new Date(Date.now() - 72 * 60 * 60 * 1000),
    },
  ]);

  // Blockchain stats - TODO: Replace with real API
  readonly blockHeight = signal('1,247,583');
  readonly totalTxCount = signal('89,412');

  readonly stats = computed(() => [
    {
      type: 'pending',
      icon: 'pending_actions',
      value: this.pendingCount(),
      label: 'Pending Approvals',
      change: null,
    },
    {
      type: 'approved',
      icon: 'check_circle',
      value: this.approvedCount(),
      label: 'Approved Today',
      change: 15,
    },
    {
      type: 'rejected',
      icon: 'cancel',
      value: this.rejectedCount(),
      label: 'Rejected Today',
      change: -8,
    },
  ]);

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

  private loadData(): void {
    // Reset error state before loading
    this.hasError.set(false);

    this.api
      .get<{ data: ApprovalResponseDto[] }>('/approvals/pending', { limit: 10 })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response) => {
          const approvals = Array.isArray(response) ? response : response?.data || [];
          this.pendingApprovals.set(approvals);
          this.pendingCount.set(approvals.length);
          this.loading.set(false);
        },
        error: (err) => {
          console.error('Failed to load pending approvals:', err);
          this.notification.error('Failed to load pending approvals. Please try again.');
          this.hasError.set(true);
          this.loading.set(false);
        },
      });
  }

  ngOnDestroy(): void {
    // Clear any pending timeouts
    if (this.copyTimeoutId) {
      clearTimeout(this.copyTimeoutId);
      this.copyTimeoutId = null;
    }
  }

  /** Retry loading data - clears error state */
  retryLoad(): void {
    this.loadData();
  }

  formatAddress(address: string): string {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  }

  formatHash(hash: string): string {
    if (!hash) return '';
    return `${hash.slice(0, 10)}...${hash.slice(-6)}`;
  }

  copyAddress(): void {
    navigator.clipboard.writeText(this.wallet().address);
    this.copied.set(true);
    this.notification.success('Address copied to clipboard');

    // Clear any existing timeout before setting a new one
    if (this.copyTimeoutId) {
      clearTimeout(this.copyTimeoutId);
    }
    this.copyTimeoutId = setTimeout(() => {
      this.copied.set(false);
      this.copyTimeoutId = null;
    }, 2000);
  }

  copyHash(hash: string): void {
    navigator.clipboard.writeText(hash);
    this.notification.success('Transaction hash copied');
  }
}
