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 { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
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 { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { EmptyStateComponent } from '../../../shared/components/empty-state/empty-state.component';
import { AuditService } from '../services/audit.service';
import { AuditLogDto, AuditAction, ActorType } from '../../../api/models';

@Component({
  selector: 'app-audit-list',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatCardModule,
    MatTableModule,
    MatPaginatorModule,
    MatFormFieldModule,
    MatSelectModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
    PageHeaderComponent,
    EmptyStateComponent,
  ],
  template: `
    <div class="page-container">
      <app-page-header title="Audit Logs" subtitle="System activity and changes" />

      <mat-card class="filters-card">
        <mat-card-content>
          <div class="filters">
            <mat-form-field appearance="outline" class="filter-field">
              <mat-label>Entity Type</mat-label>
              <mat-select [formControl]="entityTypeFilter">
                <mat-option value="">All Types</mat-option>
                <mat-option value="request">Requests</mat-option>
                <mat-option value="document">Documents</mat-option>
                <mat-option value="approval">Approvals</mat-option>
                <mat-option value="department">Departments</mat-option>
                <mat-option value="workflow">Workflows</mat-option>
              </mat-select>
            </mat-form-field>

            <mat-form-field appearance="outline" class="filter-field">
              <mat-label>Action</mat-label>
              <mat-select [formControl]="actionFilter">
                <mat-option value="">All Actions</mat-option>
                @for (action of actions; track action) {
                  <mat-option [value]="action">{{ action }}</mat-option>
                }
              </mat-select>
            </mat-form-field>

            <mat-form-field appearance="outline" class="filter-field">
              <mat-label>Actor Type</mat-label>
              <mat-select [formControl]="actorTypeFilter">
                <mat-option value="">All Actors</mat-option>
                @for (type of actorTypes; track type) {
                  <mat-option [value]="type">{{ type }}</mat-option>
                }
              </mat-select>
            </mat-form-field>

            <button mat-button (click)="clearFilters()">
              <mat-icon>clear</mat-icon>
              Clear
            </button>
          </div>
        </mat-card-content>
      </mat-card>

      <mat-card>
        <mat-card-content>
          @if (loading()) {
            <div class="loading-container">
              <mat-spinner diameter="48"></mat-spinner>
            </div>
          } @else if (logs().length === 0) {
            <app-empty-state
              icon="history"
              title="No audit logs"
              message="No audit logs match your current filters."
            />
          } @else {
            <table mat-table [dataSource]="logs()">
              <ng-container matColumnDef="timestamp">
                <th mat-header-cell *matHeaderCellDef>Timestamp</th>
                <td mat-cell *matCellDef="let row">
                  @if (row.timestamp || row.createdAt) {
                    <span class="timestamp-value">{{ (row.timestamp || row.createdAt) | date: 'medium' }}</span>
                  } @else {
                    <span class="timestamp-missing">-</span>
                  }
                </td>
              </ng-container>

              <ng-container matColumnDef="action">
                <th mat-header-cell *matHeaderCellDef>Action</th>
                <td mat-cell *matCellDef="let row">
                  <mat-chip [class]="getActionClass(row.action)">
                    {{ row.action }}
                  </mat-chip>
                </td>
              </ng-container>

              <ng-container matColumnDef="entityType">
                <th mat-header-cell *matHeaderCellDef>Entity</th>
                <td mat-cell *matCellDef="let row">
                  <a
                    [routerLink]="[row.entityType, row.entityId]"
                    class="entity-link"
                  >
                    {{ row.entityType }}
                  </a>
                </td>
              </ng-container>

              <ng-container matColumnDef="actorType">
                <th mat-header-cell *matHeaderCellDef>Actor</th>
                <td mat-cell *matCellDef="let row">
                  <span class="actor-info">
                    {{ row.actorType }}
                    <span class="actor-id">{{ row.actorId | slice: 0 : 8 }}</span>
                  </span>
                </td>
              </ng-container>

              <ng-container matColumnDef="details">
                <th mat-header-cell *matHeaderCellDef></th>
                <td mat-cell *matCellDef="let row">
                  <button
                    mat-icon-button
                    [routerLink]="[row.entityType, row.entityId]"
                  >
                    <mat-icon>chevron_right</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]="[10, 25, 50, 100]"
              (page)="onPageChange($event)"
              showFirstLastButtons
            />
          }
        </mat-card-content>
      </mat-card>
    </div>
  `,
  styles: [
    `
      .filters-card {
        margin-bottom: 16px;
      }

      .filters {
        display: flex;
        gap: 16px;
        align-items: center;
        flex-wrap: wrap;
      }

      .filter-field {
        width: 180px;
      }

      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      table {
        width: 100%;
      }

      .entity-link {
        color: #1976d2;
        text-decoration: none;
        font-weight: 500;

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

      .actor-info {
        display: flex;
        flex-direction: column;
      }

      .actor-id {
        font-size: 0.75rem;
        color: rgba(0, 0, 0, 0.54);
        font-family: monospace;
      }

      .timestamp-value {
        font-size: 0.875rem;
        color: #333;
      }

      .timestamp-missing {
        color: #999;
        font-style: italic;
      }

      .action-create {
        background-color: #c8e6c9 !important;
        color: #2e7d32 !important;
      }

      .action-update {
        background-color: #bbdefb !important;
        color: #1565c0 !important;
      }

      .action-delete {
        background-color: #ffcdd2 !important;
        color: #c62828 !important;
      }

      .action-approve {
        background-color: #c8e6c9 !important;
        color: #2e7d32 !important;
      }

      .action-reject {
        background-color: #ffcdd2 !important;
        color: #c62828 !important;
      }

      .mat-column-details {
        width: 48px;
      }
    `,
  ],
})
export class AuditListComponent implements OnInit, OnDestroy {
  private readonly auditService = inject(AuditService);
  private readonly destroyRef = inject(DestroyRef);

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly logs = signal<AuditLogDto[]>([]);
  readonly totalItems = signal(0);
  readonly pageSize = signal(25);
  readonly pageIndex = signal(0);

  readonly entityTypeFilter = new FormControl('');
  readonly actionFilter = new FormControl('');
  readonly actorTypeFilter = new FormControl('');

  readonly displayedColumns = ['timestamp', 'action', 'entityType', 'actorType', 'details'];
  readonly actions: AuditAction[] = ['CREATE', 'UPDATE', 'DELETE', 'APPROVE', 'REJECT', 'SUBMIT', 'CANCEL', 'DOWNLOAD'];
  readonly actorTypes: ActorType[] = ['APPLICANT', 'DEPARTMENT', 'SYSTEM', 'ADMIN'];

  ngOnInit(): void {
    this.loadLogs();

    this.entityTypeFilter.valueChanges
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => this.onFilterChange());
    this.actionFilter.valueChanges
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => this.onFilterChange());
    this.actorTypeFilter.valueChanges
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => this.onFilterChange());
  }

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

    this.auditService
      .getAuditLogs({
        page: this.pageIndex() + 1,
        limit: this.pageSize(),
        entityType: this.entityTypeFilter.value || undefined,
        action: (this.actionFilter.value as AuditAction) || undefined,
        actorType: (this.actorTypeFilter.value as ActorType) || undefined,
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response) => {
          this.logs.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.loadLogs();
  }

  onFilterChange(): void {
    this.pageIndex.set(0);
    this.loadLogs();
  }

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

  clearFilters(): void {
    this.entityTypeFilter.setValue('');
    this.actionFilter.setValue('');
    this.actorTypeFilter.setValue('');
  }

  getActionClass(action: string): string {
    return `action-${action.toLowerCase()}`;
  }
}
