import { Component, Input, Output, EventEmitter, OnInit, OnDestroy, inject, signal, computed, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { Clipboard } from '@angular/cdk/clipboard';
import { forkJoin, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ApprovalService } from '../services/approval.service';
import { ApprovalActionComponent } from '../approval-action/approval-action.component';
import { DepartmentService } from '../../departments/services/department.service';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { ApprovalResponseDto, BlockchainTransactionDto, DepartmentResponseDto } from '../../../api/models';

interface WorkflowStage {
  id: string;
  departmentId: string;
  departmentName: string;
  departmentCode?: string;
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'CHANGES_REQUESTED' | 'WAITING';
  remarks?: string;
  rejectionReason?: string;
  approvedBy?: string;
  completedAt?: string;
  createdAt: string;
  requiredDocuments?: string[];
}

interface BlockchainRecord {
  txHash: string;
  type: string;
  status: 'PENDING' | 'CONFIRMED' | 'FAILED';
  blockNumber?: number;
  timestamp: string;
  tokenId?: string;
  gasUsed?: number;
}

interface ActivityLog {
  id: string;
  action: string;
  actor: string;
  actorType: 'DEPARTMENT' | 'SYSTEM' | 'APPLICANT';
  details: string;
  timestamp: string;
}

@Component({
  selector: 'app-approval-workflow-timeline',
  standalone: true,
  imports: [
    CommonModule,
    MatCardModule,
    MatIconModule,
    MatButtonModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    MatChipsModule,
    MatDividerModule,
    MatExpansionModule,
    MatDialogModule,
  ],
  template: `
    <div class="workflow-container">
      <!-- Header -->
      <div class="workflow-header">
        <div class="header-icon">
          <mat-icon>account_tree</mat-icon>
        </div>
        <div class="header-content">
          <h2>Approval Workflow</h2>
          <p class="subtitle">Track progress across departments</p>
        </div>
        <div class="overall-status">
          <div class="status-indicator" [class]="overallStatus()">
            <mat-icon>{{ getOverallStatusIcon() }}</mat-icon>
            <span>{{ formatOverallStatus() }}</span>
          </div>
        </div>
      </div>

      @if (loading()) {
        <div class="loading-container">
          <mat-spinner diameter="40"></mat-spinner>
          <p>Loading workflow...</p>
        </div>
      } @else {
        <!-- Progress Bar -->
        <div class="progress-section">
          <div class="progress-bar-wrapper">
            <div class="progress-bar" [style.width.%]="progressPercentage()"></div>
          </div>
          <div class="progress-text">
            <span>{{ completedStages() }} of {{ totalStages() }} departments</span>
            <span class="percentage">{{ progressPercentage() }}% complete</span>
          </div>
        </div>

        <!-- Workflow Timeline -->
        <div class="timeline-section">
          <h3 class="section-title">
            <mat-icon>timeline</mat-icon>
            Department Approvals
          </h3>

          <div class="workflow-timeline">
            @for (stage of stages(); track stage.departmentId; let i = $index; let isLast = $last) {
              <div class="timeline-stage" [class.completed]="isStageCompleted(stage)" [class.current]="isStageCurrent(stage)" [class.waiting]="stage.status === 'WAITING'" [class.has-feedback]="stage.remarks || stage.rejectionReason">
                <!-- Connector Line -->
                @if (!isLast) {
                  <div class="connector-line" [class.active]="isStageCompleted(stage)"></div>
                }

                <!-- Stage Marker -->
                <div class="stage-marker" [class]="stage.status.toLowerCase()">
                  @switch (stage.status) {
                    @case ('APPROVED') {
                      <mat-icon>check</mat-icon>
                    }
                    @case ('REJECTED') {
                      <mat-icon>close</mat-icon>
                    }
                    @case ('CHANGES_REQUESTED') {
                      <mat-icon>edit_note</mat-icon>
                    }
                    @case ('PENDING') {
                      <mat-icon>hourglass_top</mat-icon>
                    }
                    @default {
                      <span class="stage-number">{{ i + 1 }}</span>
                    }
                  }
                </div>

                <!-- Stage Content -->
                <div class="stage-content" [class]="'status-' + stage.status.toLowerCase()">
                  <div class="stage-card">
                    <div class="stage-header">
                      <div class="dept-info">
                        <span class="department-name">{{ stage.departmentName }}</span>
                        @if (stage.departmentCode) {
                          <span class="department-code">
                            <mat-icon>badge</mat-icon>
                            {{ stage.departmentCode }}
                          </span>
                        }
                        @if (stage.approvedBy) {
                          <span class="reviewer-name">
                            <mat-icon>person</mat-icon>
                            {{ stage.approvedBy }}
                          </span>
                        }
                      </div>
                      <mat-chip [class]="'status-' + stage.status.toLowerCase()">
                        {{ formatStatus(stage.status) }}
                      </mat-chip>
                    </div>

                    <div class="stage-meta-row">
                      @if (stage.completedAt) {
                        <div class="stage-meta">
                          <mat-icon>event</mat-icon>
                          <span>{{ stage.completedAt | date:'medium' }}</span>
                        </div>
                      } @else if (stage.status === 'PENDING') {
                        @if (canTakeAction(stage)) {
                          <div class="action-required-notice">
                            <mat-icon>notification_important</mat-icon>
                            <span>Your action required</span>
                          </div>
                        } @else {
                          <div class="stage-meta pending-notice">
                            <mat-icon>pending_actions</mat-icon>
                            <span>Awaiting department review</span>
                          </div>
                        }
                      } @else if (stage.status === 'WAITING') {
                        <div class="stage-meta waiting-notice">
                          <mat-icon>queue</mat-icon>
                          <span>Waiting for previous approval</span>
                        </div>
                      }
                    </div>

                    <!-- Action Buttons for Department Users -->
                    @if (canTakeAction(stage)) {
                      <div class="action-buttons-section">
                        <div class="action-prompt">
                          <mat-icon>gavel</mat-icon>
                          <span>Take action on this request:</span>
                        </div>
                        <div class="action-buttons">
                          <button
                            mat-raised-button
                            color="primary"
                            (click)="openApprovalDialog(stage, 'approve')"
                          >
                            <mat-icon>check</mat-icon>
                            Approve
                          </button>
                          <button
                            mat-raised-button
                            color="warn"
                            (click)="openApprovalDialog(stage, 'reject')"
                          >
                            <mat-icon>close</mat-icon>
                            Reject
                          </button>
                          <button
                            mat-stroked-button
                            color="accent"
                            (click)="openApprovalDialog(stage, 'changes')"
                          >
                            <mat-icon>edit_note</mat-icon>
                            Request Changes
                          </button>
                        </div>
                      </div>
                    }

                    <!-- Department Feedback Section - More Prominent -->
                    @if (stage.remarks || stage.rejectionReason || stage.requiredDocuments?.length) {
                      <div class="feedback-section" [class]="'feedback-' + stage.status.toLowerCase()">
                        <div class="feedback-header">
                          <mat-icon>{{ getFeedbackIcon(stage.status) }}</mat-icon>
                          <span>{{ getFeedbackTitle(stage.status) }}</span>
                        </div>

                        @if (stage.rejectionReason) {
                          <div class="feedback-reason">
                            <span class="reason-label">Reason:</span>
                            <span class="reason-value">{{ formatRejectionReason(stage.rejectionReason) }}</span>
                          </div>
                        }

                        @if (stage.remarks) {
                          <div class="feedback-remarks">
                            <p>{{ stage.remarks }}</p>
                          </div>
                        }

                        @if (stage.requiredDocuments?.length) {
                          <div class="required-docs">
                            <span class="docs-label">Required Documents:</span>
                            <ul>
                              @for (doc of stage.requiredDocuments; track doc) {
                                <li>{{ doc }}</li>
                              }
                            </ul>
                          </div>
                        }
                      </div>
                    }
                  </div>
                </div>
              </div>
            }

            <!-- Final Stage: Blockchain/NFT Minting (Only after ALL approvals) -->
            @if (showBlockchainStage()) {
              <div class="timeline-stage blockchain-stage"
                   [class.completed]="isBlockchainConfirmed()"
                   [class.pending]="allApprovalsComplete() && !isBlockchainConfirmed()"
                   [class.waiting]="!allApprovalsComplete() && !hasRejection()">

                <div class="stage-marker blockchain"
                     [class.confirmed]="isBlockchainConfirmed()"
                     [class.pending]="allApprovalsComplete() && !isBlockchainConfirmed()"
                     [class.waiting]="!allApprovalsComplete()">
                  @if (isBlockchainConfirmed()) {
                    <mat-icon>verified</mat-icon>
                  } @else if (allApprovalsComplete()) {
                    <mat-icon>hourglass_top</mat-icon>
                  } @else if (hasRejection()) {
                    <mat-icon>block</mat-icon>
                  } @else {
                    <mat-icon>lock</mat-icon>
                  }
                </div>

                <div class="stage-content blockchain-content">
                  <div class="stage-card blockchain-card" [class.rejected-card]="hasRejection()">
                    <div class="stage-header">
                      <div class="dept-info">
                        <span class="department-name blockchain-title">
                          <mat-icon class="nft-icon">token</mat-icon>
                          License NFT Minting
                        </span>
                        <span class="blockchain-subtitle">Final step after all department approvals</span>
                      </div>
                      @if (isBlockchainConfirmed()) {
                        <mat-chip class="status-confirmed">
                          <mat-icon>verified</mat-icon>
                          Minted
                        </mat-chip>
                      } @else if (allApprovalsComplete()) {
                        <mat-chip class="status-pending">
                          <mat-icon>pending</mat-icon>
                          Minting...
                        </mat-chip>
                      } @else if (hasRejection()) {
                        <mat-chip class="status-rejected">
                          <mat-icon>block</mat-icon>
                          Not Applicable
                        </mat-chip>
                      } @else {
                        <mat-chip class="status-waiting">
                          <mat-icon>lock</mat-icon>
                          Awaiting Approvals
                        </mat-chip>
                      }
                    </div>

                    @if (isBlockchainConfirmed() && blockchainRecord()) {
                      <!-- NFT Successfully Minted -->
                      <div class="blockchain-details">
                        @if (blockchainRecord()?.tokenId) {
                          <div class="blockchain-field nft-field">
                            <span class="field-label">License NFT Token ID</span>
                            <span class="field-value token-id">#{{ blockchainRecord()?.tokenId }}</span>
                          </div>
                        }

                        <div class="blockchain-grid">
                          <div class="blockchain-field">
                            <span class="field-label">Transaction Hash</span>
                            <div class="hash-container" (click)="copyHash(blockchainRecord()?.txHash || '')">
                              <code class="tx-hash">{{ truncateHash(blockchainRecord()?.txHash || '') }}</code>
                              <mat-icon class="copy-icon" matTooltip="Copy hash">content_copy</mat-icon>
                            </div>
                          </div>

                          @if (blockchainRecord()?.blockNumber) {
                            <div class="blockchain-field">
                              <span class="field-label">Block Number</span>
                              <span class="field-value">{{ blockchainRecord()?.blockNumber | number }}</span>
                            </div>
                          }

                          @if (blockchainRecord()?.gasUsed) {
                            <div class="blockchain-field">
                              <span class="field-label">Gas Used</span>
                              <span class="field-value">{{ blockchainRecord()?.gasUsed | number }}</span>
                            </div>
                          }

                          <div class="blockchain-field">
                            <span class="field-label">Minted On</span>
                            <span class="field-value">{{ blockchainRecord()?.timestamp | date:'medium' }}</span>
                          </div>
                        </div>
                      </div>

                      <div class="blockchain-verified-banner">
                        <mat-icon>shield</mat-icon>
                        <span>This license NFT is cryptographically secured on the blockchain and cannot be tampered with.</span>
                      </div>
                    } @else if (hasRejection()) {
                      <!-- Request Rejected - No NFT -->
                      <div class="blockchain-rejected">
                        <mat-icon>info</mat-icon>
                        <span>NFT cannot be minted because the request was rejected by one or more departments.</span>
                      </div>
                    } @else if (allApprovalsComplete()) {
                      <!-- All Approved - Minting in Progress -->
                      <div class="blockchain-minting">
                        <div class="minting-animation">
                          <mat-icon>token</mat-icon>
                        </div>
                        <div class="minting-text">
                          <strong>All departments approved!</strong>
                          <span>Your License NFT is being minted on the blockchain...</span>
                        </div>
                      </div>
                    } @else {
                      <!-- Waiting for Approvals -->
                      <div class="blockchain-waiting">
                        <mat-icon>info</mat-icon>
                        <div class="waiting-text">
                          <span>NFT will be minted automatically after <strong>all departments</strong> approve your application.</span>
                          <span class="approval-progress">{{ completedStages() }} of {{ totalStages() }} departments approved</span>
                        </div>
                      </div>
                    }
                  </div>
                </div>
              </div>
            }
          </div>
        </div>

        <!-- Activity Logs -->
        <mat-expansion-panel class="activity-panel">
          <mat-expansion-panel-header>
            <mat-panel-title>
              <mat-icon>history</mat-icon>
              Activity Log
            </mat-panel-title>
            <mat-panel-description>
              {{ activityLogs().length }} events
            </mat-panel-description>
          </mat-expansion-panel-header>

          <div class="activity-list">
            @for (log of activityLogs(); track log.id) {
              <div class="activity-item">
                <div class="activity-icon" [class]="getActivityIconClass(log.action)">
                  <mat-icon>{{ getActivityIcon(log.action) }}</mat-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-header">
                    <span class="activity-action">{{ formatActivityAction(log.action) }}</span>
                    <span class="activity-time">{{ log.timestamp | date:'short' }}</span>
                  </div>
                  <p class="activity-details">{{ log.details }}</p>
                  <span class="activity-actor">
                    <mat-icon>{{ log.actorType === 'SYSTEM' ? 'smart_toy' : 'person' }}</mat-icon>
                    {{ log.actor }}
                  </span>
                </div>
              </div>
            }

            @if (activityLogs().length === 0) {
              <div class="empty-activity">
                <mat-icon>event_busy</mat-icon>
                <p>No activity recorded yet</p>
              </div>
            }
          </div>
        </mat-expansion-panel>
      }
    </div>
  `,
  styles: [`
    .workflow-container {
      background: white;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    }

    /* Header - Fixed contrast */
    .workflow-header {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 24px;
      background: linear-gradient(135deg, var(--dbim-blue-dark, #1D0A69) 0%, var(--dbim-blue-mid, #2563EB) 100%);
      color: white;
    }

    .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: 24px;
        width: 24px;
        height: 24px;
        color: white;
      }
    }

    .header-content {
      flex: 1;

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

      .subtitle {
        margin: 4px 0 0;
        font-size: 0.85rem;
        color: rgba(255, 255, 255, 0.85);
      }
    }

    .overall-status {
      .status-indicator {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        border-radius: 24px;
        font-size: 0.875rem;
        font-weight: 600;

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

        &.in-progress {
          background: rgba(255, 193, 7, 0.25);
          color: #FFF176;
        }

        &.approved {
          background: rgba(76, 175, 80, 0.25);
          color: #A5D6A7;
        }

        &.rejected {
          background: rgba(244, 67, 54, 0.25);
          color: #EF9A9A;
        }

        &.pending {
          background: rgba(255, 255, 255, 0.2);
          color: white;
        }
      }
    }

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

      p {
        color: #666;
        margin: 0;
      }
    }

    /* Progress Section */
    .progress-section {
      padding: 20px 24px;
      background: #F8F9FA;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    }

    .progress-bar-wrapper {
      height: 10px;
      background: #E0E0E0;
      border-radius: 5px;
      overflow: hidden;
    }

    .progress-bar {
      height: 100%;
      background: linear-gradient(90deg, #198754 0%, #28a745 100%);
      border-radius: 5px;
      transition: width 0.5s ease;
    }

    .progress-text {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      font-size: 0.85rem;
      color: #666;

      .percentage {
        font-weight: 700;
        color: #198754;
      }
    }

    /* Timeline Section */
    .timeline-section {
      padding: 24px;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 0 0 24px;
      font-size: 1.1rem;
      font-weight: 600;
      color: #1a1a1a;

      mat-icon {
        color: #2563EB;
      }
    }

    .workflow-timeline {
      position: relative;
    }

    .timeline-stage {
      display: flex;
      gap: 16px;
      padding-bottom: 24px;
      position: relative;

      &:last-child {
        padding-bottom: 0;
      }

      &.has-feedback {
        padding-bottom: 32px;
      }
    }

    .connector-line {
      position: absolute;
      left: 19px;
      top: 44px;
      width: 3px;
      height: calc(100% - 20px);
      background: #E0E0E0;
      border-radius: 2px;

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

    .stage-marker {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      font-weight: 600;
      font-size: 0.875rem;
      z-index: 1;
      transition: all 0.3s ease;

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

      .stage-number {
        color: white;
      }

      &.waiting {
        background: #F5F5F5;
        border: 2px dashed #BDBDBD;

        .stage-number {
          color: #9E9E9E;
        }
      }

      &.pending {
        background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
        box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
        animation: pulse 2s infinite;
      }

      &.approved {
        background: linear-gradient(135deg, #198754 0%, #28a745 100%);
        box-shadow: 0 4px 12px rgba(25, 135, 84, 0.3);
      }

      &.rejected {
        background: linear-gradient(135deg, #DC3545 0%, #E57373 100%);
        box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
      }

      &.changes_requested {
        background: linear-gradient(135deg, #2196F3 0%, #64B5F6 100%);
        box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
      }

      &.blockchain {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, #7C3AED 0%, #A78BFA 100%);
        box-shadow: 0 4px 16px rgba(124, 58, 237, 0.3);

        &.confirmed {
          background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
          box-shadow: 0 4px 16px rgba(16, 185, 129, 0.3);
        }

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

    @keyframes pulse {
      0%, 100% { transform: scale(1); }
      50% { transform: scale(1.05); }
    }

    .stage-content {
      flex: 1;
    }

    .stage-card {
      background: white;
      border-radius: 12px;
      padding: 16px;
      border: 1px solid #E5E7EB;
      transition: all 0.2s ease;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }
    }

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

    .dept-info {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .department-name {
      font-size: 1rem;
      font-weight: 600;
      color: #1a1a1a;
      display: flex;
      align-items: center;
      gap: 8px;

      .nft-icon {
        color: #7C3AED;
      }
    }

    .department-code {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 0.75rem;
      color: #6B7280;
      background: rgba(107, 114, 128, 0.1);
      padding: 2px 8px;
      border-radius: 4px;
      font-family: 'Monaco', 'Consolas', monospace;

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

    .reviewer-name {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 0.8rem;
      color: #2563EB;

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

    mat-chip {
      font-size: 0.7rem !important;
      min-height: 24px !important;
      padding: 0 10px !important;
      font-weight: 600 !important;

      &.status-approved, &.status-confirmed {
        background: rgba(25, 135, 84, 0.15) !important;
        color: #157347 !important;
      }

      &.status-pending {
        background: rgba(255, 152, 0, 0.15) !important;
        color: #E65100 !important;
      }

      &.status-rejected {
        background: rgba(220, 53, 69, 0.15) !important;
        color: #b02a37 !important;
      }

      &.status-changes_requested {
        background: rgba(33, 150, 243, 0.15) !important;
        color: #0d47a1 !important;
      }

      &.status-waiting {
        background: rgba(158, 158, 158, 0.15) !important;
        color: #616161 !important;
      }

      mat-icon {
        font-size: 14px !important;
        width: 14px !important;
        height: 14px !important;
        margin-right: 4px;
      }
    }

    .stage-meta-row {
      margin-top: 10px;
    }

    .stage-meta {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 0.8rem;
      color: #666;

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

      &.pending-notice {
        color: #E65100;

        mat-icon {
          color: #E65100;
        }
      }
    }

    .action-required-notice {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 0.85rem;
      font-weight: 600;
      color: #1D0A69;
      background: linear-gradient(135deg, rgba(99, 102, 241, 0.15) 0%, rgba(139, 92, 246, 0.1) 100%);
      padding: 8px 12px;
      border-radius: 8px;
      margin-top: 10px;

      mat-icon {
        font-size: 18px;
        width: 18px;
        height: 18px;
        color: #6366F1;
      }
    }

    .action-buttons-section {
      margin-top: 16px;
      padding: 16px;
      background: linear-gradient(135deg, rgba(99, 102, 241, 0.08) 0%, rgba(139, 92, 246, 0.05) 100%);
      border-radius: 12px;
      border: 1px solid rgba(99, 102, 241, 0.2);
    }

    .action-prompt {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;
      font-size: 0.9rem;
      font-weight: 600;
      color: #1D0A69;

      mat-icon {
        font-size: 20px;
        width: 20px;
        height: 20px;
        color: #6366F1;
      }
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      button {
        mat-icon {
          margin-right: 4px;
        }
      }

      &.waiting-notice {
        color: #757575;

        mat-icon {
          color: #757575;
        }
      }
    }

    /* Department Feedback Section - PROMINENT */
    .feedback-section {
      margin-top: 16px;
      padding: 16px;
      border-radius: 10px;
      border-left: 4px solid;

      &.feedback-approved {
        background: linear-gradient(135deg, rgba(25, 135, 84, 0.08) 0%, rgba(40, 167, 69, 0.05) 100%);
        border-left-color: #198754;
      }

      &.feedback-rejected {
        background: linear-gradient(135deg, rgba(220, 53, 69, 0.08) 0%, rgba(229, 115, 115, 0.05) 100%);
        border-left-color: #DC3545;
      }

      &.feedback-changes_requested {
        background: linear-gradient(135deg, rgba(33, 150, 243, 0.08) 0%, rgba(100, 181, 246, 0.05) 100%);
        border-left-color: #2196F3;
      }

      &.feedback-pending {
        background: linear-gradient(135deg, rgba(255, 152, 0, 0.08) 0%, rgba(255, 183, 77, 0.05) 100%);
        border-left-color: #FF9800;
      }
    }

    .feedback-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      font-size: 0.9rem;
      margin-bottom: 12px;

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

      .feedback-approved & {
        color: #157347;
      }

      .feedback-rejected & {
        color: #b02a37;
      }

      .feedback-changes_requested & {
        color: #0d47a1;
      }

      .feedback-pending & {
        color: #E65100;
      }
    }

    .feedback-reason {
      display: flex;
      gap: 8px;
      margin-bottom: 10px;
      padding: 10px 12px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 6px;

      .reason-label {
        font-weight: 600;
        color: #333;
        font-size: 0.85rem;
      }

      .reason-value {
        color: #DC3545;
        font-size: 0.85rem;
        font-weight: 500;
      }
    }

    .feedback-remarks {
      padding: 12px 14px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 6px;

      p {
        margin: 0;
        font-size: 0.9rem;
        color: #333;
        line-height: 1.6;
        font-style: italic;

        &::before {
          content: '"';
          font-size: 1.2rem;
          color: #888;
        }

        &::after {
          content: '"';
          font-size: 1.2rem;
          color: #888;
        }
      }
    }

    .required-docs {
      margin-top: 12px;
      padding: 12px 14px;
      background: rgba(255, 255, 255, 0.7);
      border-radius: 6px;

      .docs-label {
        font-weight: 600;
        color: #333;
        font-size: 0.85rem;
        display: block;
        margin-bottom: 8px;
      }

      ul {
        margin: 0;
        padding-left: 20px;

        li {
          color: #0d47a1;
          font-size: 0.85rem;
          margin-bottom: 4px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    /* Blockchain Section */
    .blockchain-stage {
      margin-top: 16px;
      padding-top: 24px;
      border-top: 2px dashed rgba(124, 58, 237, 0.3);
    }

    .blockchain-content {
      .stage-card {
        border-color: rgba(124, 58, 237, 0.3);
      }
    }

    .blockchain-card {
      background: linear-gradient(135deg, rgba(124, 58, 237, 0.03) 0%, rgba(167, 139, 250, 0.03) 100%);
    }

    .blockchain-title {
      color: #5B21B6 !important;
    }

    .blockchain-details {
      margin-top: 16px;
    }

    .blockchain-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
      gap: 16px;
      margin-top: 16px;
    }

    .blockchain-field {
      &.nft-field {
        text-align: center;
        padding: 20px;
        background: linear-gradient(135deg, rgba(124, 58, 237, 0.1) 0%, rgba(167, 139, 250, 0.1) 100%);
        border-radius: 12px;
        margin-bottom: 8px;

        .token-id {
          font-size: 2.5rem !important;
          font-weight: 700;
          color: #7C3AED;
          display: block;
          margin-top: 4px;
        }
      }
    }

    .field-label {
      display: block;
      font-size: 0.7rem;
      color: #888;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 4px;
      font-weight: 500;
    }

    .field-value {
      font-size: 0.9rem;
      font-weight: 600;
      color: #1a1a1a;
    }

    .hash-container {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      background: #F5F5F5;
      border-radius: 6px;
      cursor: pointer;
      transition: background 0.2s;

      &:hover {
        background: #EEEEEE;

        .copy-icon {
          opacity: 1;
          color: #2563EB;
        }
      }
    }

    .tx-hash {
      font-family: 'Monaco', 'Consolas', monospace;
      font-size: 0.8rem;
      color: #1D0A69;
    }

    .copy-icon {
      font-size: 14px !important;
      width: 14px !important;
      height: 14px !important;
      opacity: 0.5;
      transition: all 0.2s;
      color: #666;
    }

    .blockchain-verified-banner {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-top: 16px;
      padding: 14px 16px;
      background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(52, 211, 153, 0.1) 100%);
      border-radius: 10px;
      border: 1px solid rgba(16, 185, 129, 0.3);

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

      span {
        font-size: 0.85rem;
        color: #047857;
        line-height: 1.4;
        font-weight: 500;
      }
    }

    .blockchain-subtitle {
      font-size: 0.75rem;
      color: #888;
      font-weight: 400;
    }

    .rejected-card {
      background: linear-gradient(135deg, rgba(220, 53, 69, 0.03) 0%, rgba(229, 115, 115, 0.03) 100%) !important;
      border-color: rgba(220, 53, 69, 0.2) !important;
    }

    .blockchain-waiting {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      margin-top: 16px;
      padding: 16px;
      background: linear-gradient(135deg, rgba(124, 58, 237, 0.05) 0%, rgba(167, 139, 250, 0.05) 100%);
      border-radius: 10px;
      border: 1px dashed rgba(124, 58, 237, 0.3);

      mat-icon {
        font-size: 22px;
        width: 22px;
        height: 22px;
        color: #7C3AED;
        margin-top: 2px;
      }

      .waiting-text {
        display: flex;
        flex-direction: column;
        gap: 6px;

        span {
          font-size: 0.85rem;
          color: #555;
          line-height: 1.4;
        }

        .approval-progress {
          font-size: 0.8rem;
          color: #7C3AED;
          font-weight: 600;
        }
      }
    }

    .blockchain-rejected {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-top: 16px;
      padding: 16px;
      background: rgba(220, 53, 69, 0.08);
      border-radius: 10px;
      border: 1px solid rgba(220, 53, 69, 0.2);

      mat-icon {
        font-size: 22px;
        width: 22px;
        height: 22px;
        color: #DC3545;
      }

      span {
        font-size: 0.85rem;
        color: #b02a37;
        line-height: 1.4;
      }
    }

    .blockchain-minting {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-top: 16px;
      padding: 20px;
      background: linear-gradient(135deg, rgba(16, 185, 129, 0.08) 0%, rgba(52, 211, 153, 0.08) 100%);
      border-radius: 10px;
      border: 1px solid rgba(16, 185, 129, 0.3);

      .minting-animation {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        animation: mintPulse 1.5s ease-in-out infinite;

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

      .minting-text {
        display: flex;
        flex-direction: column;
        gap: 4px;

        strong {
          font-size: 0.95rem;
          color: #059669;
        }

        span {
          font-size: 0.85rem;
          color: #047857;
        }
      }
    }

    @keyframes mintPulse {
      0%, 100% {
        transform: scale(1);
        box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4);
      }
      50% {
        transform: scale(1.05);
        box-shadow: 0 0 0 10px rgba(16, 185, 129, 0);
      }
    }

    .stage-marker.blockchain.waiting {
      background: linear-gradient(135deg, #9CA3AF 0%, #D1D5DB 100%);
      box-shadow: 0 4px 12px rgba(156, 163, 175, 0.3);

      mat-icon {
        color: white;
      }
    }

    /* Activity Panel */
    .activity-panel {
      margin: 24px;
      border-radius: 12px !important;
      box-shadow: none !important;
      border: 1px solid #E5E7EB !important;
      background: #FAFAFA !important;

      ::ng-deep .mat-expansion-panel-header-title {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #333;

        mat-icon {
          color: #666;
        }
      }

      ::ng-deep .mat-expansion-panel-header-description {
        color: #888;
      }
    }

    .activity-list {
      max-height: 300px;
      overflow-y: auto;
    }

    .activity-item {
      display: flex;
      gap: 12px;
      padding: 12px 0;
      border-bottom: 1px solid #EEEEEE;

      &:last-child {
        border-bottom: none;
      }
    }

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

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

      &.approve {
        background: rgba(25, 135, 84, 0.15);
        color: #157347;
      }

      &.reject {
        background: rgba(220, 53, 69, 0.15);
        color: #b02a37;
      }

      &.submit {
        background: rgba(33, 150, 243, 0.15);
        color: #0d47a1;
      }

      &.create, &.update {
        background: rgba(124, 58, 237, 0.15);
        color: #6D28D9;
      }

      &.default {
        background: rgba(158, 158, 158, 0.15);
        color: #616161;
      }
    }

    .activity-content {
      flex: 1;
    }

    .activity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .activity-action {
      font-size: 0.875rem;
      font-weight: 600;
      color: #1a1a1a;
    }

    .activity-time {
      font-size: 0.75rem;
      color: #888;
    }

    .activity-details {
      margin: 4px 0;
      font-size: 0.8rem;
      color: #555;
      line-height: 1.4;
    }

    .activity-actor {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 0.75rem;
      color: #888;

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

    .empty-activity {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 32px;
      color: #888;

      mat-icon {
        font-size: 32px;
        width: 32px;
        height: 32px;
        margin-bottom: 8px;
        opacity: 0.5;
      }

      p {
        margin: 0;
      }
    }
  `],
})
export class ApprovalWorkflowTimelineComponent implements OnInit, OnDestroy {
  @Input({ required: true }) requestId!: string;
  @Input() txHash?: string;
  @Input() tokenId?: string;
  @Output() approvalActionTaken = new EventEmitter<void>();

  private readonly approvalService = inject(ApprovalService);
  private readonly departmentService = inject(DepartmentService);
  private readonly api = inject(ApiService);
  private readonly authService = inject(AuthService);
  private readonly clipboard = inject(Clipboard);
  private readonly dialog = inject(MatDialog);
  private readonly destroyRef = inject(DestroyRef);

  // Cache for department details to avoid repeated API calls
  private readonly departmentCache = new Map<string, DepartmentResponseDto>();

  // Store the raw approvals for action dialogs
  private rawApprovals: ApprovalResponseDto[] = [];

  readonly loading = signal(true);
  readonly stages = signal<WorkflowStage[]>([]);
  readonly blockchainRecord = signal<BlockchainRecord | null>(null);
  readonly activityLogs = signal<ActivityLog[]>([]);

  readonly totalStages = computed(() => this.stages().length);
  readonly completedStages = computed(() =>
    this.stages().filter(s => s.status === 'APPROVED').length
  );
  readonly progressPercentage = computed(() => {
    const total = this.totalStages();
    if (total === 0) return 0;
    return Math.round((this.completedStages() / total) * 100);
  });

  readonly overallStatus = computed(() => {
    const stageList = this.stages();
    if (stageList.some(s => s.status === 'REJECTED')) return 'rejected';
    if (stageList.every(s => s.status === 'APPROVED')) {
      return this.isBlockchainConfirmed() ? 'approved' : 'in-progress';
    }
    if (stageList.some(s => s.status === 'PENDING' || s.status === 'CHANGES_REQUESTED')) {
      return 'in-progress';
    }
    return 'pending';
  });

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

  ngOnDestroy(): void {
    // Cleanup handled by DestroyRef
  }

  private loadWorkflowData(): void {
    this.loading.set(true);

    // Load approvals for the request
    this.approvalService.getApprovalHistory(this.requestId)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (approvals) => {
          this.processApprovals(approvals);
          this.loadDepartmentDetails(approvals);
          this.loadBlockchainData();
          this.generateActivityLogs(approvals);
          this.loading.set(false);
        },
        error: () => {
          this.loading.set(false);
        },
      });
  }

  /**
   * Load department details for all approvals to get actual names and codes
   */
  private loadDepartmentDetails(approvals: ApprovalResponseDto[]): void {
    // Get unique department IDs
    const uniqueDeptIds = [...new Set(approvals.map(a => a.departmentId))];

    // Filter out IDs we already have cached
    const idsToFetch = uniqueDeptIds.filter(id => !this.departmentCache.has(id));

    if (idsToFetch.length === 0) {
      // All cached, just update stages
      this.updateStagesWithDepartmentDetails();
      return;
    }

    // Fetch department details for each unique ID
    const requests = idsToFetch.map(id =>
      this.departmentService.getDepartment(id).pipe(
        catchError(() => of(null)) // Ignore errors for individual departments
      )
    );

    forkJoin(requests)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (departments) => {
          // Cache the results
          departments.forEach((dept, index) => {
            if (dept) {
              this.departmentCache.set(idsToFetch[index], dept);
            }
          });
          // Update stages with department details
          this.updateStagesWithDepartmentDetails();
        },
        error: () => {
          // Silently fail - we'll just show IDs
        },
      });
  }

  /**
   * Update stages signal with cached department details
   */
  private updateStagesWithDepartmentDetails(): void {
    const currentStages = this.stages();
    const updatedStages = currentStages.map(stage => {
      const dept = this.departmentCache.get(stage.departmentId);
      if (dept) {
        return {
          ...stage,
          departmentName: dept.name || stage.departmentName,
          departmentCode: dept.code || stage.departmentCode,
        };
      }
      return stage;
    });
    this.stages.set(updatedStages);
  }

  private processApprovals(approvals: ApprovalResponseDto[]): void {
    // Store raw approvals for action dialogs
    this.rawApprovals = approvals;

    const stageList: WorkflowStage[] = approvals.map(approval => ({
      id: approval.id,
      departmentId: approval.departmentId,
      departmentName: approval.departmentName || this.formatDepartmentId(approval.departmentId),
      departmentCode: approval.departmentCode,
      status: approval.status as WorkflowStage['status'],
      remarks: approval.remarks,
      rejectionReason: approval.rejectionReason,
      approvedBy: approval.approvedBy,
      completedAt: approval.completedAt,
      createdAt: approval.createdAt,
      requiredDocuments: approval.requiredDocuments,
    }));

    this.stages.set(stageList);
  }

  private loadBlockchainData(): void {
    // Use provided inputs if available (from parent component)
    if (this.txHash) {
      this.blockchainRecord.set({
        txHash: this.txHash,
        type: 'LICENSE_MINT',
        status: 'CONFIRMED', // If we have a txHash, assume confirmed
        timestamp: new Date().toISOString(),
        tokenId: this.tokenId,
      });
      return;
    }

    // Fallback: Try to load blockchain transaction for this request via API
    // This endpoint may require admin privileges
    this.api.get<BlockchainTransactionDto[]>(`/admin/blockchain/transactions`, {
      requestId: this.requestId,
      limit: 1
    }).pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response: any) => {
          const transactions = response?.data || response || [];
          if (transactions.length > 0) {
            const tx = transactions[0];
            this.blockchainRecord.set({
              txHash: tx.txHash,
              type: tx.type,
              status: tx.status,
              blockNumber: tx.blockNumber,
              timestamp: tx.timestamp,
              tokenId: tx.data?.tokenId,
              gasUsed: tx.gasUsed,
            });
          }
        },
        error: () => {
          // Silently fail - blockchain data is optional
        },
      });
  }

  private generateActivityLogs(approvals: ApprovalResponseDto[]): void {
    const logs: ActivityLog[] = [];

    // Generate logs from approvals
    approvals.forEach((approval, index) => {
      // Creation log
      logs.push({
        id: `${approval.id}-created`,
        action: 'CREATE',
        actor: 'System',
        actorType: 'SYSTEM',
        details: `Approval request created for ${approval.departmentName}`,
        timestamp: approval.createdAt,
      });

      // Status change logs
      if (approval.status !== 'PENDING') {
        logs.push({
          id: `${approval.id}-${approval.status}`,
          action: approval.status,
          actor: approval.approvedBy || approval.departmentName,
          actorType: 'DEPARTMENT',
          details: this.getStatusChangeDetails(approval),
          timestamp: approval.completedAt || approval.updatedAt,
        });
      }
    });

    // Sort by timestamp descending (newest first)
    logs.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
    this.activityLogs.set(logs);
  }

  private getStatusChangeDetails(approval: ApprovalResponseDto): string {
    switch (approval.status) {
      case 'APPROVED':
        return `${approval.departmentName} approved the request${approval.remarks ? `: ${approval.remarks}` : ''}`;
      case 'REJECTED':
        return `${approval.departmentName} rejected the request: ${this.formatRejectionReason(approval.rejectionReason || '')}`;
      case 'CHANGES_REQUESTED':
        return `${approval.departmentName} requested changes${approval.remarks ? `: ${approval.remarks}` : ''}`;
      default:
        return `Status updated to ${approval.status}`;
    }
  }

  // Helper methods
  isStageCompleted(stage: WorkflowStage): boolean {
    return stage.status === 'APPROVED';
  }

  isStageCurrent(stage: WorkflowStage): boolean {
    return stage.status === 'PENDING' || stage.status === 'CHANGES_REQUESTED';
  }

  showBlockchainStage(): boolean {
    return this.stages().length > 0;
  }

  allApprovalsComplete(): boolean {
    return this.stages().length > 0 && this.stages().every(s => s.status === 'APPROVED');
  }

  hasRejection(): boolean {
    return this.stages().some(s => s.status === 'REJECTED');
  }

  isBlockchainConfirmed(): boolean {
    return this.blockchainRecord()?.status === 'CONFIRMED';
  }

  isBlockchainPending(): boolean {
    return this.blockchainRecord()?.status === 'PENDING';
  }

  formatStatus(status: string): string {
    return status.replace(/_/g, ' ');
  }

  formatRejectionReason(reason: string): string {
    return reason.replace(/_/g, ' ').toLowerCase().replace(/^\w/, c => c.toUpperCase());
  }

  getFeedbackIcon(status: string): string {
    switch (status) {
      case 'APPROVED': return 'check_circle';
      case 'REJECTED': return 'cancel';
      case 'CHANGES_REQUESTED': return 'edit_note';
      default: return 'comment';
    }
  }

  getFeedbackTitle(status: string): string {
    switch (status) {
      case 'APPROVED': return 'Department Approval Notes';
      case 'REJECTED': return 'Rejection Details';
      case 'CHANGES_REQUESTED': return 'Changes Requested';
      default: return 'Department Feedback';
    }
  }

  formatDepartmentId(deptId: string): string {
    return deptId
      .replace(/_/g, ' ')
      .toLowerCase()
      .replace(/\b\w/g, c => c.toUpperCase())
      .replace(/Dept/g, 'Department');
  }

  getOverallStatusIcon(): string {
    switch (this.overallStatus()) {
      case 'approved': return 'verified';
      case 'rejected': return 'cancel';
      case 'in-progress': return 'pending_actions';
      default: return 'hourglass_empty';
    }
  }

  formatOverallStatus(): string {
    switch (this.overallStatus()) {
      case 'approved': return 'Fully Approved';
      case 'rejected': return 'Rejected';
      case 'in-progress': return 'In Progress';
      default: return 'Pending';
    }
  }

  truncateHash(hash: string): string {
    if (!hash || hash.length <= 20) return hash || '';
    return `${hash.substring(0, 10)}...${hash.substring(hash.length - 6)}`;
  }

  copyHash(hash: string): void {
    this.clipboard.copy(hash);
  }

  getActivityIcon(action: string): string {
    switch (action) {
      case 'APPROVED': return 'check_circle';
      case 'REJECTED': return 'cancel';
      case 'CHANGES_REQUESTED': return 'edit';
      case 'CREATE': return 'add_circle';
      case 'SUBMIT': return 'send';
      default: return 'info';
    }
  }

  getActivityIconClass(action: string): string {
    switch (action) {
      case 'APPROVED': return 'approve';
      case 'REJECTED': return 'reject';
      case 'CHANGES_REQUESTED':
      case 'CREATE': return 'create';
      case 'SUBMIT': return 'submit';
      default: return 'default';
    }
  }

  formatActivityAction(action: string): string {
    switch (action) {
      case 'APPROVED': return 'Approval Granted';
      case 'REJECTED': return 'Request Rejected';
      case 'CHANGES_REQUESTED': return 'Changes Requested';
      case 'CREATE': return 'Request Created';
      case 'SUBMIT': return 'Request Submitted';
      default: return action.replace(/_/g, ' ');
    }
  }

  /**
   * Check if the current department user can take action on a specific stage
   */
  canTakeAction(stage: WorkflowStage): boolean {
    // Only department users can take actions
    if (!this.authService.isDepartment()) return false;

    // Can only act on PENDING stages
    if (stage.status !== 'PENDING') return false;

    // Check if current user's department ID matches this stage
    const currentUser = this.authService.getCurrentUser();
    if (!currentUser?.departmentId) return false;

    // Compare department IDs (case-insensitive for UUID format variations)
    return currentUser.departmentId.toLowerCase() === stage.departmentId.toLowerCase();
  }

  /**
   * Open approval action dialog
   */
  openApprovalDialog(stage: WorkflowStage, action: 'approve' | 'reject' | 'changes'): void {
    // Find the raw approval DTO for this stage
    const approval = this.rawApprovals.find(a => a.id === stage.id);
    if (!approval) return;

    const dialogRef = this.dialog.open(ApprovalActionComponent, {
      data: { approval, action },
      width: '500px',
    });

    dialogRef.afterClosed()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((result) => {
        if (result) {
          // Reload workflow data
          this.loadWorkflowData();
          // Emit event so parent can reload if needed
          this.approvalActionTaken.emit();
        }
      });
  }
}
