import { Component, OnInit, OnDestroy, inject, signal, DestroyRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ApiService } from '../../../core/services/api.service';

interface PlatformStats {
  totalRequests: number;
  totalApplicants: number;
  activeApplicants: number;
  totalDepartments: number;
  activeDepartments: number;
  totalDocuments: number;
  totalBlockchainTransactions: number;
}

@Component({
  selector: 'app-admin-stats',
  standalone: true,
  imports: [CommonModule, MatCardModule, MatIconModule, MatProgressSpinnerModule],
  template: `
    @if (!loading()) {
      <div class="stats-grid">
        <mat-card class="stat-card primary">
          <div class="stat-icon-wrapper">
            <mat-icon class="stat-icon">description</mat-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats()?.totalRequests ?? 0 }}</div>
            <div class="stat-label">Total Requests</div>
          </div>
        </mat-card>

        <mat-card class="stat-card success">
          <div class="stat-icon-wrapper">
            <mat-icon class="stat-icon">business</mat-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats()?.activeDepartments ?? 0 }} / {{ stats()?.totalDepartments ?? 0 }}</div>
            <div class="stat-label">Active Departments</div>
          </div>
        </mat-card>

        <mat-card class="stat-card info">
          <div class="stat-icon-wrapper">
            <mat-icon class="stat-icon">people</mat-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats()?.activeApplicants ?? 0 }} / {{ stats()?.totalApplicants ?? 0 }}</div>
            <div class="stat-label">Active Applicants</div>
          </div>
        </mat-card>

        <mat-card class="stat-card warning">
          <div class="stat-icon-wrapper">
            <mat-icon class="stat-icon">receipt_long</mat-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats()?.totalBlockchainTransactions ?? 0 }}</div>
            <div class="stat-label">Blockchain Transactions</div>
          </div>
        </mat-card>

        <mat-card class="stat-card secondary">
          <div class="stat-icon-wrapper">
            <mat-icon class="stat-icon">folder</mat-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats()?.totalDocuments ?? 0 }}</div>
            <div class="stat-label">Total Documents</div>
          </div>
        </mat-card>
      </div>
    } @else {
      <div class="loading-container">
        <mat-spinner diameter="40"></mat-spinner>
        <p>Loading statistics...</p>
      </div>
    }
  `,
  styles: [
    `
      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 20px;
        margin-bottom: 24px;
      }

      .stat-card {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 24px;
        border-radius: 16px !important;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          width: 100px;
          height: 100px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.1);
          transform: translate(30%, -30%);
        }

        &:hover {
          transform: translateY(-4px);
          box-shadow: var(--shadow-elevated);
        }

        &.primary {
          background: linear-gradient(135deg, #1D0A69 0%, #2563EB 100%) !important;
          color: white !important;
        }
        &.success {
          background: linear-gradient(135deg, #059669 0%, #10b981 100%) !important;
          color: white !important;
        }
        &.info {
          background: linear-gradient(135deg, #0d6efd 0%, #60a5fa 100%) !important;
          color: white !important;
        }
        &.warning {
          background: linear-gradient(135deg, #d97706 0%, #f59e0b 100%) !important;
          color: white !important;
        }
        &.secondary {
          background: linear-gradient(135deg, #8B5CF6 0%, #6366F1 100%) !important;
          color: white !important;
        }
      }

      .stat-icon-wrapper {
        width: 56px;
        height: 56px;
        border-radius: 14px;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(10px);

        .stat-icon {
          font-size: 28px !important;
          width: 28px !important;
          height: 28px !important;
          color: white !important;
        }
      }

      .stat-content {
        flex: 1;
        position: relative;
        z-index: 1;
      }

      .stat-value {
        font-size: 28px;
        font-weight: 700;
        margin-bottom: 4px;
        letter-spacing: -0.02em;
        color: white !important;
      }

      .stat-label {
        font-size: 13px;
        font-weight: 500;
        color: rgba(255, 255, 255, 0.9) !important;
      }

      .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 48px;
        gap: 16px;

        p {
          color: #6b7280;
          font-size: 14px;
        }
      }

    `,
  ],
})
export class AdminStatsComponent implements OnInit, OnDestroy {
  private readonly api = inject(ApiService);
  private readonly destroyRef = inject(DestroyRef);

  readonly stats = signal<PlatformStats | null>(null);
  readonly loading = signal(true);
  readonly hasError = signal(false);

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

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

    this.api.get<PlatformStats>('/admin/stats')
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (result) => {
          this.stats.set(result ?? null);
          this.loading.set(false);
        },
        error: (error) => {
          console.error('Failed to load stats:', error);
          this.hasError.set(true);
          this.loading.set(false);
        },
      });
  }

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

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