import { Component, OnInit, OnDestroy, inject, signal, 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 { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { StatusBadgeComponent } from '../../../shared/components/status-badge/status-badge.component';
import { EmptyStateComponent } from '../../../shared/components/empty-state/empty-state.component';
import { WorkflowService } from '../services/workflow.service';
import { WorkflowResponseDto } from '../../../api/models';

@Component({
  selector: 'app-workflow-list',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatTableModule,
    MatPaginatorModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    PageHeaderComponent,
    StatusBadgeComponent,
    EmptyStateComponent,
  ],
  template: `
    <div class="page-container">
      <app-page-header title="Workflows" subtitle="Manage approval workflows">
        <button mat-stroked-button routerLink="new" class="header-btn">
          <mat-icon>add</mat-icon>
          Form Builder
        </button>
        <button mat-raised-button color="primary" routerLink="builder" class="header-btn">
          <mat-icon>account_tree</mat-icon>
          Visual Builder
        </button>
      </app-page-header>

      <mat-card>
        <mat-card-content>
          @if (loading()) {
            <div class="loading-container">
              <mat-spinner diameter="48"></mat-spinner>
            </div>
          } @else if (workflows().length === 0) {
            <app-empty-state
              icon="account_tree"
              title="No workflows"
              message="No approval workflows have been created yet."
            >
              <button mat-raised-button color="primary" routerLink="new">
                <mat-icon>add</mat-icon>
                Create Workflow
              </button>
            </app-empty-state>
          } @else {
            <table mat-table [dataSource]="workflows()">
              <ng-container matColumnDef="name">
                <th mat-header-cell *matHeaderCellDef>Name</th>
                <td mat-cell *matCellDef="let row">
                  <a [routerLink]="[row.id]" class="workflow-link">{{ row.name }}</a>
                </td>
              </ng-container>

              <ng-container matColumnDef="workflowType">
                <th mat-header-cell *matHeaderCellDef>Workflow Type</th>
                <td mat-cell *matCellDef="let row">{{ formatType(row.workflowType) }}</td>
              </ng-container>

              <ng-container matColumnDef="stages">
                <th mat-header-cell *matHeaderCellDef>Stages</th>
                <td mat-cell *matCellDef="let row">
                  <mat-chip>{{ row.definition?.stages?.length || 0 }} stages</mat-chip>
                </td>
              </ng-container>

              <ng-container matColumnDef="status">
                <th mat-header-cell *matHeaderCellDef>Status</th>
                <td mat-cell *matCellDef="let row">
                  <app-status-badge [status]="row.isActive ? 'ACTIVE' : 'INACTIVE'" />
                </td>
              </ng-container>

              <ng-container matColumnDef="actions">
                <th mat-header-cell *matHeaderCellDef></th>
                <td mat-cell *matCellDef="let row">
                  <button mat-icon-button [routerLink]="[row.id]" matTooltip="Preview">
                    <mat-icon>visibility</mat-icon>
                  </button>
                  <button mat-icon-button [routerLink]="['builder', row.id]" matTooltip="Visual Editor">
                    <mat-icon>account_tree</mat-icon>
                  </button>
                  <button mat-icon-button [routerLink]="[row.id, 'edit']" matTooltip="Form Editor">
                    <mat-icon>edit</mat-icon>
                  </button>
                </td>
              </ng-container>

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

            <mat-paginator
              [length]="totalItems()"
              [pageSize]="pageSize()"
              [pageIndex]="pageIndex()"
              [pageSizeOptions]="[5, 10, 25]"
              (page)="onPageChange($event)"
              showFirstLastButtons
            />
          }
        </mat-card-content>
      </mat-card>
    </div>
  `,
  styles: [
    `
      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      table {
        width: 100%;
      }

      .workflow-link {
        color: var(--dbim-blue-mid, #2563EB);
        text-decoration: none;
        font-weight: 500;

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

      .mat-column-actions {
        width: 140px;
        text-align: right;
      }

      .header-btn {
        margin-left: 8px;
      }
    `,
  ],
})
export class WorkflowListComponent implements OnInit, OnDestroy {
  private readonly workflowService = inject(WorkflowService);
  private readonly destroyRef = inject(DestroyRef);

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly workflows = signal<WorkflowResponseDto[]>([]);
  readonly totalItems = signal(0);
  readonly pageSize = signal(10);
  readonly pageIndex = signal(0);

  readonly displayedColumns = ['name', 'workflowType', 'stages', 'status', 'actions'];

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

  loadWorkflows(): void {
    this.loading.set(true);
    this.hasError.set(false);

    this.workflowService.getWorkflows(this.pageIndex() + 1, this.pageSize())
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response) => {
          this.workflows.set(response?.data ?? []);
          this.totalItems.set(response?.total ?? 0);
          this.loading.set(false);
        },
        error: () => {
          this.hasError.set(true);
          this.loading.set(false);
        },
      });
  }

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

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

  onPageChange(event: PageEvent): void {
    this.pageIndex.set(event.pageIndex);
    this.pageSize.set(event.pageSize);
    this.loadWorkflows();
  }

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