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 { MatDividerModule } from '@angular/material/divider';
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 { DepartmentService } from '../services/department.service';
import { NotificationService } from '../../../core/services/notification.service';
import { DepartmentResponseDto } from '../../../api/models';

@Component({
  selector: 'app-department-detail',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatDividerModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    PageHeaderComponent,
    StatusBadgeComponent,
  ],
  template: `
    <div class="page-container">
      @if (loading()) {
        <div class="loading-container">
          <mat-spinner diameter="48"></mat-spinner>
        </div>
      } @else if (department(); as dept) {
        <app-page-header [title]="dept.name" [subtitle]="dept.code">
          <button mat-button routerLink="/departments">
            <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="detail-grid">
          <mat-card class="info-card">
            <mat-card-header>
              <mat-card-title>Department Information</mat-card-title>
            </mat-card-header>
            <mat-card-content>
              <div class="info-row">
                <span class="label">Status</span>
                <app-status-badge [status]="dept.isActive ? 'ACTIVE' : 'INACTIVE'" />
              </div>
              <div class="info-row">
                <span class="label">Code</span>
                <span class="value code">{{ dept.code }}</span>
              </div>
              @if (dept.description) {
                <div class="info-row">
                  <span class="label">Description</span>
                  <span class="value">{{ dept.description }}</span>
                </div>
              }
              @if (dept.contactEmail) {
                <div class="info-row">
                  <span class="label">Email</span>
                  <span class="value">{{ dept.contactEmail }}</span>
                </div>
              }
              @if (dept.contactPhone) {
                <div class="info-row">
                  <span class="label">Phone</span>
                  <span class="value">{{ dept.contactPhone }}</span>
                </div>
              }
              @if (dept.webhookUrl) {
                <div class="info-row">
                  <span class="label">Webhook URL</span>
                  <span class="value url">{{ dept.webhookUrl }}</span>
                </div>
              }
              <div class="info-row">
                <span class="label">Created</span>
                <span class="value">{{ dept.createdAt | date: 'medium' }}</span>
              </div>
            </mat-card-content>
          </mat-card>

          <mat-card class="actions-card">
            <mat-card-header>
              <mat-card-title>Actions</mat-card-title>
            </mat-card-header>
            <mat-card-content>
              <div class="action-buttons">
                <button
                  mat-stroked-button
                  (click)="toggleActive()"
                  [color]="dept.isActive ? 'warn' : 'primary'"
                >
                  <mat-icon>{{ dept.isActive ? 'block' : 'check_circle' }}</mat-icon>
                  {{ dept.isActive ? 'Deactivate' : 'Activate' }}
                </button>
                <button mat-stroked-button color="primary" (click)="regenerateApiKey()">
                  <mat-icon>vpn_key</mat-icon>
                  Regenerate API Key
                </button>
                <mat-divider></mat-divider>
                <button mat-stroked-button color="warn" (click)="deleteDepartment()">
                  <mat-icon>delete</mat-icon>
                  Delete Department
                </button>
              </div>
            </mat-card-content>
          </mat-card>
        </div>
      }
    </div>
  `,
  styles: [
    `
      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      .detail-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 24px;
      }

      @media (max-width: 960px) {
        .detail-grid {
          grid-template-columns: 1fr;
        }
      }

      .info-card mat-card-content,
      .actions-card mat-card-content {
        padding-top: 16px;
      }

      .info-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding: 12px 0;
        border-bottom: 1px solid #eee;

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

      .label {
        color: rgba(0, 0, 0, 0.54);
        font-size: 0.875rem;
        flex-shrink: 0;
        margin-right: 16px;
      }

      .value {
        text-align: right;
        word-break: break-word;

        &.code {
          font-family: monospace;
          font-weight: 500;
          color: #1976d2;
        }

        &.url {
          font-size: 0.875rem;
          font-family: monospace;
        }
      }

      .action-buttons {
        display: flex;
        flex-direction: column;
        gap: 12px;

        mat-divider {
          margin: 8px 0;
        }
      }
    `,
  ],
})
export class DepartmentDetailComponent implements OnInit {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly departmentService = inject(DepartmentService);
  private readonly notification = inject(NotificationService);
  private readonly dialog = inject(MatDialog);

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly department = signal<DepartmentResponseDto | null>(null);

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

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

    this.departmentService.getDepartment(id).subscribe({
      next: (dept) => {
        this.department.set(dept);
        this.loading.set(false);
      },
      error: (err) => {
        console.error('Failed to load department:', err);
        this.notification.error('Failed to load department. Please try again.');
        this.hasError.set(true);
        this.loading.set(false);
      },
    });
  }

  toggleActive(): void {
    const dept = this.department();
    if (!dept) return;

    const action = dept.isActive ? 'deactivate' : 'activate';
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: `${dept.isActive ? 'Deactivate' : 'Activate'} Department`,
        message: `Are you sure you want to ${action} ${dept.name}?`,
        confirmText: dept.isActive ? 'Deactivate' : 'Activate',
        confirmColor: dept.isActive ? 'warn' : 'primary',
      },
    });

    dialogRef.afterClosed().subscribe((confirmed) => {
      if (confirmed) {
        this.departmentService.toggleActive(dept.id, !dept.isActive).subscribe({
          next: () => {
            this.notification.success(`Department ${action}d`);
            this.loadDepartment();
          },
        });
      }
    });
  }

  regenerateApiKey(): void {
    const dept = this.department();
    if (!dept) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Regenerate API Key',
        message:
          'This will invalidate the current API key. The department will need to update their integration. Continue?',
        confirmText: 'Regenerate',
        confirmColor: 'warn',
      },
    });

    dialogRef.afterClosed().subscribe((confirmed) => {
      if (confirmed) {
        this.departmentService.regenerateApiKey(dept.id).subscribe({
          next: (result) => {
            this.showCredentialsDialog(result.apiKey, result.apiSecret);
          },
          error: () => {
            this.notification.error('Failed to regenerate API key');
          },
        });
      }
    });
  }

  private showCredentialsDialog(apiKey: string, apiSecret: string): void {
    this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'New API Credentials Generated',
        message: `Please save these credentials securely. The API Secret will not be shown again.\n\n` +
                 `API Key: ${apiKey}\n\n` +
                 `API Secret: ${apiSecret}`,
        confirmText: 'I have saved these credentials',
        confirmColor: 'primary',
        hideCancel: true,
      },
      disableClose: true,
      width: '500px',
    });
  }

  deleteDepartment(): void {
    const dept = this.department();
    if (!dept) return;

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

    dialogRef.afterClosed().subscribe((confirmed) => {
      if (confirmed) {
        this.departmentService.deleteDepartment(dept.id).subscribe({
          next: () => {
            this.notification.success('Department deleted');
            this.router.navigate(['/departments']);
          },
        });
      }
    });
  }
}
