import { Component, OnInit, OnDestroy, inject, signal, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { RouterModule, ActivatedRoute } 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 { 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 { 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 { RequestService } from '../services/request.service';
import { AuthService } from '../../../core/services/auth.service';
import { RequestResponseDto, RequestStatus, RequestType } from '../../../api/models';

@Component({
  selector: 'app-request-list',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatCardModule,
    MatTableModule,
    MatPaginatorModule,
    MatFormFieldModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatTooltipModule,
    PageHeaderComponent,
    StatusBadgeComponent,
    EmptyStateComponent,
  ],
  templateUrl: './request-list.component.html',
  styles: [
    `
      /* Summary Stats Section */
      .stats-summary {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
      }

      .stat-card {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 20px;
        background: var(--dbim-white);
        border-radius: 16px;
        box-shadow: var(--shadow-card);
        border: 1px solid rgba(29, 10, 105, 0.06);
        transition: all 0.25s ease;

        &:hover {
          box-shadow: var(--shadow-card-hover);
          transform: translateY(-2px);
        }

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;

          mat-icon {
            font-size: 24px;
            width: 24px;
            height: 24px;
            color: white;
          }

          &.total {
            background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--dbim-blue-mid) 100%);
          }

          &.pending {
            background: linear-gradient(135deg, #d97706 0%, #f59e0b 100%);
          }

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

          &.rejected {
            background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
          }
        }

        .stat-content {
          .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--dbim-brown);
            line-height: 1.2;
          }

          .stat-label {
            font-size: 13px;
            color: var(--dbim-grey-2);
            font-weight: 500;
          }
        }
      }

      /* Filters Section */
      .filters-section {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px 20px;
        background: var(--dbim-linen);
        border-radius: 12px;
        margin-bottom: 24px;
        flex-wrap: wrap;

        .filter-label {
          font-size: 14px;
          font-weight: 500;
          color: var(--dbim-grey-3);
          display: flex;
          align-items: center;
          gap: 6px;

          mat-icon {
            font-size: 18px;
            width: 18px;
            height: 18px;
          }
        }

        .filters {
          display: flex;
          gap: 12px;
          flex: 1;
          flex-wrap: wrap;
        }

        .filter-field {
          width: 180px;
        }
      }

      /* Table Styles */
      .table-container {
        overflow-x: auto;
        border-radius: 12px;
        border: 1px solid rgba(29, 10, 105, 0.06);
      }

      table {
        width: 100%;
        min-width: 800px;
      }

      .mat-mdc-header-row {
        background: var(--dbim-linen);
      }

      .mat-mdc-row {
        cursor: pointer;
        transition: all 0.15s ease;

        &:hover {
          background-color: rgba(29, 10, 105, 0.02);
        }
      }

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

        .loading-text {
          font-size: 14px;
          color: var(--dbim-grey-2);
        }
      }

      .request-number {
        font-weight: 600;
        color: var(--dbim-blue-mid);
        font-family: 'Roboto Mono', monospace;
        font-size: 13px;

        &:hover {
          color: var(--dbim-blue-dark);
        }
      }

      .type-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 10px;
        background: var(--dbim-blue-subtle);
        border-radius: 6px;
        font-size: 12px;
        font-weight: 500;
        color: var(--dbim-blue-mid);

        mat-icon {
          font-size: 14px;
          width: 14px;
          height: 14px;
        }
      }

      .date-cell {
        font-size: 13px;
        color: var(--dbim-grey-3);

        .date-main {
          display: block;
        }

        .date-time {
          font-size: 11px;
          color: var(--dbim-grey-2);
        }
      }

      /* Quick Action Buttons */
      .quick-actions {
        display: flex;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.15s ease;
      }

      .mat-mdc-row:hover .quick-actions {
        opacity: 1;
      }

      .action-btn {
        width: 32px;
        height: 32px;
        min-width: 32px;

        mat-icon {
          font-size: 18px;
          width: 18px;
          height: 18px;
        }
      }
    `,
  ],
})
export class RequestListComponent implements OnInit, OnDestroy {
  private readonly requestService = inject(RequestService);
  private readonly authService = inject(AuthService);
  private readonly route = inject(ActivatedRoute);
  private readonly destroyRef = inject(DestroyRef);

  readonly loading = signal(true);
  readonly hasError = signal(false);
  readonly requests = signal<RequestResponseDto[]>([]);
  readonly totalItems = signal(0);
  readonly pageSize = signal(10);
  readonly pageIndex = signal(0);

  readonly statusFilter = new FormControl<RequestStatus | ''>('');
  readonly typeFilter = new FormControl<RequestType | ''>('');

  readonly displayedColumns = ['requestNumber', 'requestType', 'status', 'createdAt', 'updatedAt', 'actions'];
  readonly statuses: RequestStatus[] = [
    'DRAFT',
    'SUBMITTED',
    'IN_REVIEW',
    'PENDING_RESUBMISSION',
    'APPROVED',
    'REJECTED',
    'CANCELLED',
  ];
  readonly requestTypes: RequestType[] = [
    'NEW_LICENSE',
    'RENEWAL',
    'AMENDMENT',
    'MODIFICATION',
    'CANCELLATION',
  ];

  readonly isApplicant = this.authService.isApplicant;

  ngOnInit(): void {
    this.route.queryParams
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((params) => {
        if (params['status']) {
          this.statusFilter.setValue(params['status']);
        }
        this.loadRequests();
      });

    this.statusFilter.valueChanges
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => {
        this.pageIndex.set(0);
        this.loadRequests();
      });

    this.typeFilter.valueChanges
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => {
        this.pageIndex.set(0);
        this.loadRequests();
      });
  }

  loadRequests(): void {
    this.loading.set(true);
    this.hasError.set(false);
    const user = this.authService.getCurrentUser();

    this.requestService
      .getRequests({
        page: this.pageIndex() + 1,
        limit: this.pageSize(),
        status: this.statusFilter.value || undefined,
        requestType: this.typeFilter.value || undefined,
        applicantId: this.isApplicant() ? user?.id : undefined,
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (response) => {
          const data = response?.data ?? [];
          // Use mock data if API returns empty results (demo mode)
          if (data.length === 0) {
            const mockData = this.getMockRequests();
            this.requests.set(mockData);
            this.totalItems.set(mockData.length);
          } else {
            this.requests.set(data);
            this.totalItems.set(response.total ?? 0);
          }
          this.loading.set(false);
        },
        error: () => {
          // Use mock data when API is unavailable
          const mockData = this.getMockRequests();
          this.requests.set(mockData);
          this.totalItems.set(mockData.length);
          this.hasError.set(true);
          this.loading.set(false);
        },
      });
  }

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

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

  private getMockRequests(): RequestResponseDto[] {
    return [
      {
        id: 'req-001',
        requestNumber: 'GOA-2026-001',
        requestType: 'NEW_LICENSE',
        status: 'SUBMITTED',
        applicantId: 'user-001',
        currentStageId: 'stage-001',
        metadata: { businessName: 'Goa Beach Resort' },
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      },
      {
        id: 'req-002',
        requestNumber: 'GOA-2026-002',
        requestType: 'RENEWAL',
        status: 'IN_REVIEW',
        applicantId: 'user-002',
        currentStageId: 'stage-002',
        metadata: { businessName: 'Panjim Restaurant' },
        createdAt: new Date(Date.now() - 86400000).toISOString(),
        updatedAt: new Date().toISOString(),
      },
      {
        id: 'req-003',
        requestNumber: 'GOA-2026-003',
        requestType: 'AMENDMENT',
        status: 'APPROVED',
        applicantId: 'user-001',
        currentStageId: 'stage-003',
        metadata: { businessName: 'Calangute Hotel' },
        blockchainTxHash: '0x123abc456def',
        createdAt: new Date(Date.now() - 172800000).toISOString(),
        updatedAt: new Date(Date.now() - 86400000).toISOString(),
        approvedAt: new Date(Date.now() - 86400000).toISOString(),
      },
      {
        id: 'req-004',
        requestNumber: 'GOA-2026-004',
        requestType: 'NEW_LICENSE',
        status: 'PENDING_RESUBMISSION',
        applicantId: 'user-003',
        currentStageId: 'stage-001',
        metadata: { businessName: 'Margao Traders' },
        createdAt: new Date(Date.now() - 259200000).toISOString(),
        updatedAt: new Date(Date.now() - 43200000).toISOString(),
      },
      {
        id: 'req-005',
        requestNumber: 'GOA-2026-005',
        requestType: 'CANCELLATION',
        status: 'REJECTED',
        applicantId: 'user-002',
        currentStageId: 'stage-004',
        metadata: { businessName: 'Vasco Shops' },
        createdAt: new Date(Date.now() - 345600000).toISOString(),
        updatedAt: new Date(Date.now() - 172800000).toISOString(),
      },
    ];
  }

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

  formatType(type: string): string {
    return type.replace(/_/g, ' ');
  }

  formatStatus(status: string): string {
    return status.replace(/_/g, ' ').toLowerCase().replace(/^\w/, (c) => c.toUpperCase());
  }

  getTypeIcon(type: string): string {
    switch (type) {
      case 'NEW_LICENSE':
        return 'add_circle';
      case 'RENEWAL':
        return 'autorenew';
      case 'AMENDMENT':
        return 'edit_note';
      case 'MODIFICATION':
        return 'tune';
      case 'CANCELLATION':
        return 'cancel';
      default:
        return 'description';
    }
  }

  getPendingCount(): number {
    return this.requests().filter(
      (r) => r.status === 'SUBMITTED' || r.status === 'IN_REVIEW' || r.status === 'PENDING_RESUBMISSION'
    ).length;
  }

  getApprovedCount(): number {
    return this.requests().filter((r) => r.status === 'APPROVED').length;
  }

  getRejectedCount(): number {
    return this.requests().filter((r) => r.status === 'REJECTED').length;
  }
}
