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 { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatMenuModule } from '@angular/material/menu';
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 { EmptyStateComponent } from '../../../shared/components/empty-state/empty-state.component';
import { ConfirmDialogComponent } from '../../../shared/components/confirm-dialog/confirm-dialog.component';
import { WebhookService } from '../services/webhook.service';
import { NotificationService } from '../../../core/services/notification.service';
import { WebhookResponseDto } from '../../../api/models';

@Component({
  selector: 'app-webhook-list',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatTableModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatMenuModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    PageHeaderComponent,
    StatusBadgeComponent,
    EmptyStateComponent,
  ],
  template: `
    <div class="page-container">
      <app-page-header title="Webhooks" subtitle="Manage event notifications">
        <button mat-raised-button color="primary" routerLink="new">
          <mat-icon>add</mat-icon>
          Register Webhook
        </button>
      </app-page-header>

      <mat-card>
        <mat-card-content>
          @if (loading()) {
            <div class="loading-container">
              <mat-spinner diameter="48"></mat-spinner>
            </div>
          } @else if (webhooks().length === 0) {
            <app-empty-state
              icon="webhook"
              title="No webhooks"
              message="Register a webhook to receive event notifications."
            >
              <button mat-raised-button color="primary" routerLink="new">
                <mat-icon>add</mat-icon>
                Register Webhook
              </button>
            </app-empty-state>
          } @else {
            <table mat-table [dataSource]="webhooks()">
              <ng-container matColumnDef="url">
                <th mat-header-cell *matHeaderCellDef>URL</th>
                <td mat-cell *matCellDef="let row">
                  <span class="url-cell">{{ row.url }}</span>
                </td>
              </ng-container>

              <ng-container matColumnDef="events">
                <th mat-header-cell *matHeaderCellDef>Events</th>
                <td mat-cell *matCellDef="let row">
                  <div class="events-chips">
                    @for (event of (row.events || []).slice(0, 2); track event) {
                      <mat-chip>{{ formatEvent(event) }}</mat-chip>
                    }
                    @if ((row.events?.length || 0) > 2) {
                      <mat-chip>+{{ (row.events?.length || 0) - 2 }}</mat-chip>
                    }
                  </div>
                </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 [matMenuTriggerFor]="menu">
                    <mat-icon>more_vert</mat-icon>
                  </button>
                  <mat-menu #menu="matMenu">
                    <button mat-menu-item (click)="testWebhook(row)">
                      <mat-icon>send</mat-icon>
                      <span>Test</span>
                    </button>
                    <button mat-menu-item [routerLink]="[row.id, 'logs']">
                      <mat-icon>history</mat-icon>
                      <span>View Logs</span>
                    </button>
                    <button mat-menu-item [routerLink]="[row.id, 'edit']">
                      <mat-icon>edit</mat-icon>
                      <span>Edit</span>
                    </button>
                    <button mat-menu-item (click)="deleteWebhook(row)">
                      <mat-icon color="warn">delete</mat-icon>
                      <span>Delete</span>
                    </button>
                  </mat-menu>
                </td>
              </ng-container>

              <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
              <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
            </table>
          }
        </mat-card-content>
      </mat-card>
    </div>
  `,
  styles: [
    `
      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      table {
        width: 100%;
      }

      .url-cell {
        font-family: monospace;
        font-size: 0.875rem;
        max-width: 300px;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .events-chips {
        display: flex;
        gap: 4px;
        flex-wrap: wrap;
      }

      .mat-column-actions {
        width: 60px;
        text-align: right;
      }
    `,
  ],
})
export class WebhookListComponent implements OnInit, OnDestroy {
  private readonly webhookService = inject(WebhookService);
  private readonly notification = inject(NotificationService);
  private readonly dialog = inject(MatDialog);
  private readonly destroyRef = inject(DestroyRef);

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly webhooks = signal<WebhookResponseDto[]>([]);

  readonly displayedColumns = ['url', 'events', 'status', 'actions'];

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

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

    this.webhookService.getWebhooks()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (data) => {
          this.webhooks.set(data ?? []);
          this.loading.set(false);
        },
        error: () => {
          this.hasError.set(true);
          this.loading.set(false);
        },
      });
  }

  formatEvent(event: string): string {
    return event?.replace(/_/g, ' ').toLowerCase() ?? '';
  }

  testWebhook(webhook: WebhookResponseDto): void {
    if (!webhook?.id) return;

    this.webhookService.testWebhook(webhook.id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (result) => {
          if (result?.success) {
            this.notification.success(`Webhook test successful (${result.statusCode})`);
          } else {
            this.notification.error(`Webhook test failed: ${result?.error || result?.statusMessage || 'Unknown error'}`);
          }
        },
        error: (err) => {
          this.notification.error('Operation failed. Please try again.');
          console.error('Error:', err);
        },
      });
  }

  deleteWebhook(webhook: WebhookResponseDto): void {
    if (!webhook?.id) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Delete Webhook',
        message: 'Are you sure you want to delete this webhook?',
        confirmText: 'Delete',
        confirmColor: 'warn',
      },
    });

    dialogRef.afterClosed()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((confirmed) => {
        if (confirmed) {
          this.webhookService.deleteWebhook(webhook.id)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
              next: () => {
                this.notification.success('Webhook deleted');
                this.loadWebhooks();
              },
              error: (err) => {
                this.notification.error('Operation failed. Please try again.');
                console.error('Error:', err);
              },
            });
        }
      });
  }

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

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