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 { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatChipsModule } from '@angular/material/chips';
import { StatusBadgeComponent } from '../../../shared/components/status-badge/status-badge.component';
import { ApiService } from '../../../core/services/api.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { RequestResponseDto, PaginatedRequestsResponse } from '../../../api/models';

interface ApplicantStats {
  totalRequests: number;
  pendingRequests: number;
  approvedLicenses: number;
  documentsUploaded: number;
  blockchainRecords: number;
}

@Component({
  selector: 'app-applicant-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    MatChipsModule,
    StatusBadgeComponent,
  ],
  template: `
    <div class="page-container">
      <!-- Welcome Section -->
      <section class="welcome-section">
        <div class="welcome-content">
          <div class="welcome-text">
            <span class="greeting">{{ getGreeting() }}</span>
            <h1>{{ currentUser()?.name || 'Applicant' }}</h1>
            <p class="subtitle">Manage your license applications and track their progress</p>
          </div>
          <div class="quick-actions">
            <button mat-raised-button color="primary" class="action-btn primary" routerLink="/requests/new">
              <mat-icon>add</mat-icon>
              New Application
            </button>
            <button mat-stroked-button class="action-btn" routerLink="/requests">
              <mat-icon>list_alt</mat-icon>
              My Requests
            </button>
          </div>
        </div>
      </section>

      <!-- Stats Cards -->
      <section class="stats-section">
        <div class="stats-grid">
          <mat-card class="stat-card pending" routerLink="/requests" [queryParams]="{ status: 'IN_REVIEW' }">
            <div class="stat-icon-wrapper">
              <mat-icon>hourglass_top</mat-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ pendingCount() }}</div>
              <div class="stat-label">Pending Review</div>
            </div>
            <div class="stat-decoration"></div>
          </mat-card>

          <mat-card class="stat-card approved" routerLink="/requests" [queryParams]="{ status: 'APPROVED' }">
            <div class="stat-icon-wrapper">
              <mat-icon>verified</mat-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ approvedCount() }}</div>
              <div class="stat-label">Approved Licenses</div>
            </div>
            <div class="stat-decoration"></div>
          </mat-card>

          <mat-card class="stat-card documents" routerLink="/requests">
            <div class="stat-icon-wrapper">
              <mat-icon>folder_open</mat-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ documentsCount() }}</div>
              <div class="stat-label">Documents Uploaded</div>
            </div>
            <div class="stat-decoration"></div>
          </mat-card>

          <mat-card class="stat-card blockchain">
            <div class="stat-icon-wrapper">
              <mat-icon>link</mat-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ blockchainCount() }}</div>
              <div class="stat-label">Blockchain Records</div>
            </div>
            <div class="stat-decoration"></div>
          </mat-card>
        </div>
      </section>

      <!-- Main Content Grid -->
      <div class="content-grid">
        <!-- Left Column: Recent Requests -->
        <div class="content-main">
          <mat-card class="section-card">
            <div class="card-header">
              <div class="header-left">
                <mat-icon>description</mat-icon>
                <h2>Recent Applications</h2>
              </div>
              <button mat-button color="primary" routerLink="/requests">
                View All
                <mat-icon>arrow_forward</mat-icon>
              </button>
            </div>

            <div class="card-content">
              @if (loading()) {
                <div class="loading-container">
                  <mat-spinner diameter="32"></mat-spinner>
                </div>
              } @else if (recentRequests().length === 0) {
                <div class="empty-state-inline">
                  <mat-icon>inbox</mat-icon>
                  <p>No applications yet</p>
                  <button mat-stroked-button color="primary" routerLink="/requests/new">
                    Create Your First Application
                  </button>
                </div>
              } @else {
                <div class="requests-list">
                  @for (request of recentRequests(); track request.id) {
                    <div class="request-item" [routerLink]="['/requests', request.id]">
                      <div class="request-left">
                        <div class="request-icon" [class]="getStatusClass(request.status)">
                          <mat-icon>{{ getStatusIcon(request.status) }}</mat-icon>
                        </div>
                        <div class="request-info">
                          <span class="request-number">{{ request.requestNumber }}</span>
                          <span class="request-type">
                            {{ formatRequestType(request.requestType) }}
                          </span>
                        </div>
                      </div>
                      <div class="request-right">
                        <app-status-badge [status]="request.status" />
                        <span class="request-date">{{ formatDate(request.createdAt) }}</span>
                        <mat-icon class="chevron">chevron_right</mat-icon>
                      </div>
                    </div>
                  }
                </div>
              }
            </div>
          </mat-card>

          <!-- Quick Actions Card -->
          <mat-card class="section-card quick-actions-card">
            <div class="card-header">
              <div class="header-left">
                <mat-icon>flash_on</mat-icon>
                <h2>Quick Actions</h2>
              </div>
            </div>
            <div class="card-content">
              <div class="actions-grid">
                <div class="action-item" routerLink="/requests/new">
                  <div class="action-icon license">
                    <mat-icon>post_add</mat-icon>
                  </div>
                  <span>New License</span>
                </div>
                <div class="action-item" routerLink="/requests/new" [queryParams]="{ type: 'RENEWAL' }">
                  <div class="action-icon renewal">
                    <mat-icon>autorenew</mat-icon>
                  </div>
                  <span>Renew License</span>
                </div>
                <div class="action-item" routerLink="/requests">
                  <div class="action-icon track">
                    <mat-icon>track_changes</mat-icon>
                  </div>
                  <span>Track Status</span>
                </div>
                <div class="action-item" routerLink="/help">
                  <div class="action-icon help">
                    <mat-icon>help_outline</mat-icon>
                  </div>
                  <span>Get Help</span>
                </div>
              </div>
            </div>
          </mat-card>
        </div>

      </div>
    </div>
  `,
  styles: [`
    .page-container {
      padding: 0;
    }

    /* Welcome Section */
    .welcome-section {
      background: linear-gradient(135deg, #1D0A69 0%, #2563EB 100%);
      color: white;
      padding: 32px;
      margin: -24px -24px 24px -24px;
      position: relative;
      overflow: hidden;
    }

    .welcome-section::before {
      content: '';
      position: absolute;
      top: -50%;
      right: -10%;
      width: 50%;
      height: 200%;
      background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
      pointer-events: none;
    }

    .welcome-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 24px;
      position: relative;
      z-index: 1;
    }

    .welcome-text .greeting {
      font-size: 0.9rem;
      opacity: 0.8;
      text-transform: uppercase;
      letter-spacing: 1px;
    }

    .welcome-text h1 {
      margin: 8px 0;
      font-size: 2rem;
      font-weight: 700;
    }

    .welcome-text .subtitle {
      margin: 0;
      opacity: 0.85;
      font-size: 0.95rem;
    }

    .quick-actions {
      display: flex;
      gap: 12px;
    }

    .action-btn.primary {
      background: white !important;
      color: #1D0A69 !important;
    }

    .action-btn:not(.primary) {
      color: white;
      border-color: rgba(255, 255, 255, 0.5);
    }

    .action-btn:not(.primary):hover {
      background: rgba(255, 255, 255, 0.1);
    }

    .action-btn mat-icon {
      margin-right: 8px;
    }

    /* Stats Section */
    .stats-section {
      margin-bottom: 24px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 20px;
    }

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

    .stat-card:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    .stat-card.pending {
      background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%) !important;
    }

    .stat-card.approved {
      background: linear-gradient(135deg, #059669 0%, #10b981 100%) !important;
    }

    .stat-card.documents {
      background: linear-gradient(135deg, #1D0A69 0%, #2563EB 100%) !important;
    }

    .stat-card.blockchain {
      background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%) !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);
      flex-shrink: 0;
    }

    .stat-icon-wrapper mat-icon {
      font-size: 28px;
      width: 28px;
      height: 28px;
    }

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

    .stat-value {
      font-size: 2rem;
      font-weight: 700;
      line-height: 1.2;
    }

    .stat-label {
      font-size: 0.85rem;
      opacity: 0.9;
      margin-top: 4px;
    }

    .stat-decoration {
      position: absolute;
      top: -20px;
      right: -20px;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
    }

    /* Content Grid */
    .content-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 24px;
    }

    .content-main {
      display: flex;
      flex-direction: column;
      gap: 24px;
    }

    .section-card {
      border-radius: 16px !important;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      border-bottom: 1px solid #EBEAEA;
    }

    .card-header .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .card-header .header-left mat-icon {
      color: #2563EB;
    }

    .card-header .header-left h2 {
      margin: 0;
      font-size: 1.1rem;
      font-weight: 600;
      color: #150202;
    }

    .card-header button mat-icon {
      margin-left: 4px;
      font-size: 18px;
      width: 18px;
      height: 18px;
    }

    .card-content {
      padding: 16px 24px 24px;
    }

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

    .empty-state-inline {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 48px 24px;
      color: #8E8E8E;
    }

    .empty-state-inline mat-icon {
      font-size: 48px;
      width: 48px;
      height: 48px;
      margin-bottom: 16px;
      opacity: 0.5;
    }

    .empty-state-inline p {
      margin: 0 0 16px;
    }

    /* Requests List */
    .requests-list {
      display: flex;
      flex-direction: column;
    }

    .request-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
      cursor: pointer;
      transition: background-color 0.2s;
      border-bottom: 1px solid #EBEAEA;
    }

    .request-item:last-child {
      border-bottom: none;
    }

    .request-item:hover {
      background: rgba(0, 0, 0, 0.02);
      margin: 0 -24px;
      padding: 16px 24px;
    }

    .request-left {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .request-icon {
      width: 44px;
      height: 44px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .request-icon mat-icon {
      font-size: 22px;
      width: 22px;
      height: 22px;
    }

    .request-icon.draft {
      background: rgba(158, 158, 158, 0.1);
      color: #9e9e9e;
    }

    .request-icon.submitted {
      background: rgba(33, 150, 243, 0.1);
      color: #2196f3;
    }

    .request-icon.in-review {
      background: rgba(255, 152, 0, 0.1);
      color: #ff9800;
    }

    .request-icon.approved {
      background: rgba(76, 175, 80, 0.1);
      color: #4caf50;
    }

    .request-icon.rejected {
      background: rgba(244, 67, 54, 0.1);
      color: #f44336;
    }

    .request-info {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .request-number {
      font-weight: 600;
      color: #150202;
    }

    .request-type {
      font-size: 0.8rem;
      color: #8E8E8E;
    }

    .request-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .request-date {
      font-size: 0.8rem;
      color: #8E8E8E;
    }

    .chevron {
      color: #C6C6C6;
    }

    /* Quick Actions Card */
    .actions-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;
    }

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      padding: 20px;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.2s;
      text-align: center;
    }

    .action-item:hover {
      background: #F5F5F5;
    }

    .action-item span {
      font-size: 0.85rem;
      color: #150202;
      font-weight: 500;
    }

    .action-icon {
      width: 56px;
      height: 56px;
      border-radius: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .action-icon mat-icon {
      font-size: 26px;
      width: 26px;
      height: 26px;
    }

    .action-icon.license {
      background: linear-gradient(135deg, #1D0A69, #2563EB);
      color: white;
    }

    .action-icon.renewal {
      background: linear-gradient(135deg, #059669, #10b981);
      color: white;
    }

    .action-icon.track {
      background: linear-gradient(135deg, #f59e0b, #fbbf24);
      color: white;
    }

    .action-icon.help {
      background: linear-gradient(135deg, #7c3aed, #a78bfa);
      color: white;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
      .welcome-content {
        flex-direction: column;
        align-items: flex-start;
      }
      .quick-actions {
        width: 100%;
      }
      .actions-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  `],
})
export class ApplicantDashboardComponent implements OnInit, OnDestroy {
  private readonly api = inject(ApiService);
  private readonly authService = inject(AuthService);
  private readonly notification = inject(NotificationService);
  private readonly destroyRef = inject(DestroyRef);

  readonly currentUser = this.authService.currentUser;
  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly recentRequests = signal<RequestResponseDto[]>([]);
  readonly pendingCount = signal(0);
  readonly approvedCount = signal(0);
  readonly documentsCount = signal(0);
  readonly blockchainCount = signal(0);

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

  getGreeting(): string {
    const hour = new Date().getHours();
    if (hour < 12) return 'Good Morning';
    if (hour < 17) return 'Good Afternoon';
    return 'Good Evening';
  }

  getStatusClass(status: string): string {
    return status.toLowerCase().replace(/_/g, '-');
  }

  getStatusIcon(status: string): string {
    const icons: Record<string, string> = {
      DRAFT: 'edit_note',
      SUBMITTED: 'send',
      IN_REVIEW: 'hourglass_top',
      APPROVED: 'check_circle',
      REJECTED: 'cancel',
      COMPLETED: 'verified',
    };
    return icons[status] || 'description';
  }

  formatRequestType(type: string): string {
    return type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
  }

  formatDate(date: string): string {
    const d = new Date(date);
    const now = new Date();
    const diffDays = Math.floor((now.getTime() - d.getTime()) / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return 'Yesterday';
    if (diffDays < 7) return `${diffDays} days ago`;
    return d.toLocaleDateString('en-IN', { day: 'numeric', month: 'short' });
  }

  private loadData(): void {
    const user = this.authService.getCurrentUser();
    if (!user) {
      this.loading.set(false);
      return;
    }

    // Reset error state before loading
    this.hasError.set(false);

    // Load requests with proper cleanup
    this.api
      .get<PaginatedRequestsResponse>('/requests', { applicantId: user.id, limit: 5 })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response) => {
          const requests = response.data || [];
          this.recentRequests.set(requests);
          this.calculateCounts(requests);
          this.loading.set(false);
        },
        error: (err) => {
          console.error('Failed to load requests:', err);
          this.notification.error('Failed to load your applications. Please try again.');
          this.hasError.set(true);
          this.loading.set(false);
        },
      });

    // Load applicant stats with proper cleanup
    this.api.get<ApplicantStats>(`/applicants/${user.id}/stats`)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (stats) => {
          this.documentsCount.set(stats?.documentsUploaded ?? 0);
          this.blockchainCount.set(stats?.blockchainRecords ?? 0);
        },
        error: (err) => {
          console.error('Failed to load applicant stats:', err);
          this.notification.error('Failed to load statistics.');
        },
      });
  }

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

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

  private calculateCounts(requests: RequestResponseDto[]): void {
    this.pendingCount.set(
      requests.filter((r) => ['SUBMITTED', 'IN_REVIEW'].includes(r.status)).length
    );
    this.approvedCount.set(
      requests.filter((r) => ['APPROVED', 'COMPLETED'].includes(r.status)).length
    );
  }
}
