import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { StatusBadgeComponent } from '../../../shared/components/status-badge/status-badge.component';
import { ConfirmDialogComponent } from '../../../shared/components/confirm-dialog/confirm-dialog.component';
import { WorkflowService } from '../services/workflow.service';
import { NotificationService } from '../../../core/services/notification.service';
import { WorkflowResponseDto } from '../../../api/models';

@Component({
  selector: 'app-workflow-preview',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    PageHeaderComponent,
    StatusBadgeComponent,
  ],
  template: `
    <div class="page-container">
      @if (loading()) {
        <div class="loading-container">
          <mat-spinner diameter="48"></mat-spinner>
        </div>
      } @else if (workflow(); as wf) {
        <app-page-header [title]="wf.name" [subtitle]="wf.description || 'Workflow configuration'">
          <button mat-button routerLink="/workflows">
            <mat-icon>arrow_back</mat-icon>
            Back
          </button>
          <button mat-raised-button [routerLink]="['edit']">
            <mat-icon>edit</mat-icon>
            Edit
          </button>
        </app-page-header>

        <div class="workflow-info">
          <mat-card class="info-card">
            <mat-card-content>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">Status</span>
                  <app-status-badge [status]="wf.isActive ? 'ACTIVE' : 'INACTIVE'" />
                </div>
                <div class="info-item">
                  <span class="label">Workflow Type</span>
                  <span class="value">{{ formatType(wf.workflowType) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">Total Stages</span>
                  <span class="value">{{ wf.definition?.stages?.length || 0 }}</span>
                </div>
                <div class="info-item">
                  <span class="label">Created</span>
                  <span class="value">{{ wf.createdAt | date: 'medium' }}</span>
                </div>
              </div>
            </mat-card-content>
          </mat-card>
        </div>

        <div class="stages-section">
          <h3>Approval Stages</h3>
          <div class="stages-flow">
            @for (stage of (wf.definition?.stages || []); track stage.stageId; let i = $index; let last = $last) {
              <div class="stage-item">
                <div class="stage-number">{{ i + 1 }}</div>
                <mat-card class="stage-card">
                  <div class="stage-content">
                    <div class="stage-name">{{ stage.stageName }}</div>
                    <div class="stage-dept">{{ stage.requiredApprovals?.[0]?.departmentCode || 'N/A' }}</div>
                    @if (stage.metadata?.['isRequired'] !== false) {
                      <mat-chip>Required</mat-chip>
                    }
                  </div>
                </mat-card>
                @if (!last) {
                  <div class="stage-connector">
                    <mat-icon>arrow_downward</mat-icon>
                  </div>
                }
              </div>
            }
          </div>
        </div>

        <div class="actions-section">
          <button
            mat-stroked-button
            [color]="wf.isActive ? 'warn' : 'primary'"
            (click)="toggleActive()"
          >
            <mat-icon>{{ wf.isActive ? 'block' : 'check_circle' }}</mat-icon>
            {{ wf.isActive ? 'Deactivate' : 'Activate' }}
          </button>
          <button mat-stroked-button color="warn" (click)="deleteWorkflow()">
            <mat-icon>delete</mat-icon>
            Delete Workflow
          </button>
        </div>
      }
    </div>
  `,
  styles: [
    `
      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      .workflow-info {
        margin-bottom: 32px;
      }

      .info-card mat-card-content {
        padding: 0;
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 1px;
        background-color: #eee;
      }

      .info-item {
        padding: 16px;
        background-color: white;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .label {
        font-size: 0.75rem;
        color: rgba(0, 0, 0, 0.54);
        text-transform: uppercase;
      }

      .value {
        font-weight: 500;
      }

      .stages-section {
        margin-bottom: 32px;

        h3 {
          margin: 0 0 24px;
          font-size: 1.25rem;
          font-weight: 500;
        }
      }

      .stages-flow {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .stage-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        max-width: 400px;
      }

      .stage-number {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: #1976d2;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .stage-card {
        width: 100%;
        padding: 16px;
      }

      .stage-content {
        text-align: center;
      }

      .stage-name {
        font-weight: 500;
        font-size: 1.125rem;
        margin-bottom: 4px;
      }

      .stage-dept {
        color: rgba(0, 0, 0, 0.54);
        font-size: 0.875rem;
        margin-bottom: 8px;
      }

      .stage-connector {
        padding: 8px 0;
        color: rgba(0, 0, 0, 0.26);
      }

      .actions-section {
        display: flex;
        gap: 12px;
        padding-top: 24px;
        border-top: 1px solid #eee;
      }

      @media (max-width: 768px) {
        .info-grid {
          grid-template-columns: repeat(2, 1fr);
        }
      }
    `,
  ],
})
export class WorkflowPreviewComponent implements OnInit {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly workflowService = inject(WorkflowService);
  private readonly notification = inject(NotificationService);
  private readonly dialog = inject(MatDialog);

  readonly loading = signal(true);
  readonly workflow = signal<WorkflowResponseDto | null>(null);

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

  private loadWorkflow(): void {
    const id = this.route.snapshot.paramMap.get('id');
    if (!id) {
      this.router.navigate(['/workflows']);
      return;
    }

    this.workflowService.getWorkflow(id).subscribe({
      next: (wf) => {
        this.workflow.set(wf);
        this.loading.set(false);
      },
      error: () => {
        this.notification.error('Workflow not found');
        this.router.navigate(['/workflows']);
      },
    });
  }

  formatType(type: string): string {
    return type.replace(/_/g, ' ');
  }

  toggleActive(): void {
    const wf = this.workflow();
    if (!wf) return;

    this.workflowService.toggleActive(wf.id, !wf.isActive).subscribe({
      next: () => {
        this.notification.success(wf.isActive ? 'Workflow deactivated' : 'Workflow activated');
        this.loadWorkflow();
      },
      error: (err) => {
        this.notification.error('Operation failed. Please try again.');
        console.error('Error:', err);
      },
    });
  }

  deleteWorkflow(): void {
    const wf = this.workflow();
    if (!wf) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Delete Workflow',
        message: `Are you sure you want to delete "${wf.name}"? This cannot be undone.`,
        confirmText: 'Delete',
        confirmColor: 'warn',
      },
    });

    dialogRef.afterClosed().subscribe((confirmed) => {
      if (confirmed) {
        this.workflowService.deleteWorkflow(wf.id).subscribe({
          next: () => {
            this.notification.success('Workflow deleted');
            this.router.navigate(['/workflows']);
          },
          error: (err) => {
            this.notification.error('Operation failed. Please try again.');
            console.error('Error:', err);
          },
        });
      }
    });
  }
}
