import { Component, OnInit, OnDestroy, inject, signal, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDividerModule } from '@angular/material/divider';
import { MatListModule } from '@angular/material/list';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { StatusBadgeComponent } from '../../../shared/components/status-badge/status-badge.component';
import { ConfirmDialogComponent } from '../../../shared/components/confirm-dialog/confirm-dialog.component';
import { BlockchainInfoComponent } from '../../../shared/components/blockchain-info/blockchain-info.component';
import { DocumentViewerComponent } from '../../../shared/components/document-viewer/document-viewer.component';
import { ApprovalWorkflowTimelineComponent } from '../../approvals/approval-workflow-timeline/approval-workflow-timeline.component';
import { RequestService } from '../services/request.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ApiService } from '../../../core/services/api.service';
import { RequestDetailResponseDto } from '../../../api/models';
import { DocumentUploadComponent, DocumentUploadDialogData } from '../../documents/document-upload/document-upload.component';

@Component({
  selector: 'app-request-detail',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatCardModule,
    MatTabsModule,
    MatButtonModule,
    MatIconModule,
    MatDividerModule,
    MatListModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    StatusBadgeComponent,
    BlockchainInfoComponent,
    DocumentViewerComponent,
    ApprovalWorkflowTimelineComponent,
  ],
  templateUrl: './request-detail.component.html',
  styles: [
    `
      .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 Header Card */
      .request-header-card {
        background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--dbim-blue-mid) 100%);
        border-radius: 20px;
        padding: 32px;
        color: white;
        margin-bottom: 24px;
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: -50%;
          right: -20%;
          width: 50%;
          height: 150%;
          background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
          pointer-events: none;
        }

        .header-content {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          flex-wrap: wrap;
          gap: 24px;
        }

        .header-left {
          .request-number {
            font-family: 'Roboto Mono', monospace;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 8px;
          }

          .request-title {
            font-size: 28px;
            font-weight: 700;
            margin: 0 0 8px;
            color: white;
          }

          .request-meta {
            display: flex;
            gap: 24px;
            flex-wrap: wrap;
            margin-top: 16px;

            .meta-item {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 14px;
              color: rgba(255, 255, 255, 0.9);

              mat-icon {
                font-size: 18px;
                width: 18px;
                height: 18px;
                color: rgba(255, 255, 255, 0.9);
              }
            }
          }
        }

        .header-right {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          gap: 16px;

          .status-large {
            padding: 8px 20px;
            border-radius: 24px;
            font-size: 14px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: white;

            &.status-draft {
              background: rgba(255, 255, 255, 0.2);
            }

            &.status-submitted,
            &.status-pending,
            &.status-in-review {
              background: rgba(255, 193, 7, 0.3);
            }

            &.status-approved {
              background: rgba(25, 135, 84, 0.3);
            }

            &.status-rejected {
              background: rgba(220, 53, 69, 0.3);
            }
          }

          .actions button {
            color: white;
          }
        }
      }

      .detail-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
        gap: 24px;
      }

      .info-card {
        padding: 24px;
        border-radius: 16px !important;
      }

      .info-section {
        margin-bottom: 24px;

        &:last-child {
          margin-bottom: 0;
        }

        .section-header {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 20px;

          .section-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: var(--dbim-blue-subtle);
            display: flex;
            align-items: center;
            justify-content: center;

            mat-icon {
              font-size: 20px;
              width: 20px;
              height: 20px;
              color: var(--dbim-blue-mid);
            }
          }

          h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: var(--dbim-brown);
          }
        }
      }

      .info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid var(--dbim-linen);

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

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

        .value {
          font-weight: 500;
          text-align: right;
          color: var(--dbim-brown);
        }
      }

      .blockchain-info {
        background-color: var(--dbim-linen);
        padding: 16px;
        border-radius: 12px;
        margin-top: 16px;

        .tx-hash {
          font-family: 'Roboto Mono', monospace;
          font-size: 12px;
          word-break: break-all;
          color: var(--dbim-grey-3);
        }
      }

      .actions {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;

        button {
          mat-icon {
            margin-right: 4px;
          }
        }
      }

      /* Approvals Timeline */
      .approvals-timeline {
        padding-left: 32px;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 11px;
          top: 8px;
          bottom: 8px;
          width: 2px;
          background: var(--dbim-linen);
        }
      }

      .timeline-item {
        position: relative;
        padding-bottom: 24px;

        &:last-child {
          padding-bottom: 0;
        }

        .timeline-marker {
          position: absolute;
          left: -32px;
          top: 4px;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background: var(--dbim-white);
          border: 3px solid var(--dbim-linen);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1;

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

          &.approved {
            border-color: var(--dbim-success);
            background: var(--dbim-success);
            color: white;
          }

          &.pending {
            border-color: var(--dbim-warning);
            background: var(--dbim-warning);
            color: var(--dbim-brown);
          }

          &.rejected {
            border-color: var(--dbim-error);
            background: var(--dbim-error);
            color: white;
          }
        }

        .timeline-content {
          background: var(--dbim-white);
          border-radius: 12px;
          padding: 16px;
          box-shadow: var(--shadow-card);
          border: 1px solid rgba(29, 10, 105, 0.06);
        }

        .timeline-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 8px;

          .dept-name {
            font-weight: 600;
            color: var(--dbim-brown);
          }

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

        .timeline-remarks {
          font-size: 13px;
          color: var(--dbim-grey-3);
          margin-top: 8px;
          padding-top: 8px;
          border-top: 1px solid var(--dbim-linen);
        }
      }

      .approvals-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }

      .approval-item {
        padding: 16px;
        background-color: var(--dbim-white);
        border-radius: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: var(--shadow-card);
        border: 1px solid rgba(29, 10, 105, 0.06);
        transition: all 0.2s ease;

        &:hover {
          box-shadow: var(--shadow-card-hover);
        }
      }

      .item-info {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .name {
          font-weight: 600;
          color: var(--dbim-brown);
        }

        .meta {
          font-size: 12px;
          color: var(--dbim-grey-2);
        }
      }

      /* Tab styling */
      .tab-content {
        padding: 24px 0;
      }

      .empty-state-card {
        text-align: center;
        padding: 48px;
        background: var(--dbim-linen);
        border-radius: 16px;

        mat-icon {
          font-size: 48px;
          width: 48px;
          height: 48px;
          color: var(--dbim-grey-2);
          margin-bottom: 16px;
        }

        p {
          color: var(--dbim-grey-2);
          margin: 0;
        }
      }
    `,
  ],
})
export class RequestDetailComponent implements OnInit, OnDestroy {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly requestService = inject(RequestService);
  private readonly authService = inject(AuthService);
  private readonly notification = inject(NotificationService);
  private readonly dialog = inject(MatDialog);
  private readonly api = inject(ApiService);
  private readonly destroyRef = inject(DestroyRef);

  readonly loading = signal(true);
  readonly submitting = signal(false);
  readonly loadingDocuments = signal(false);
  readonly hasError = signal(false);
  readonly request = signal<RequestDetailResponseDto | null>(null);
  readonly detailedDocuments = signal<any[]>([]);

  readonly isApplicant = this.authService.isApplicant;
  readonly isDepartment = this.authService.isDepartment;

  get canEdit(): boolean {
    const req = this.request();
    return this.isApplicant() && req?.status === 'DRAFT';
  }

  get canSubmit(): boolean {
    const req = this.request();
    return this.isApplicant() && (req?.status === 'DRAFT' || req?.status === 'PENDING_RESUBMISSION');
  }

  get canCancel(): boolean {
    const req = this.request();
    return (
      this.isApplicant() &&
      req !== null &&
      ['DRAFT', 'SUBMITTED', 'PENDING_RESUBMISSION'].includes(req.status)
    );
  }

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

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

    this.hasError.set(false);

    this.requestService.getRequest(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (data) => {
          this.request.set(data);
          this.loading.set(false);
          this.loadDetailedDocuments(id);
        },
        error: () => {
          this.hasError.set(true);
          this.notification.error('Request not found');
          this.router.navigate(['/requests']);
        },
      });
  }

  private loadDetailedDocuments(requestId: string): void {
    this.loadingDocuments.set(true);
    this.api.get<any[]>(`/requests/${requestId}/documents`)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (documents) => {
          // Map API response fields to what DocumentViewerComponent expects
          const mapped = (documents ?? []).map(doc => ({
            id: doc.id,
            name: doc.originalFilename || doc.name || 'Unknown',
            type: doc.docType || doc.type || 'OTHER',
            size: doc.fileSize || doc.size || 0,
            fileHash: doc.currentHash || doc.fileHash || '',
            url: doc.url || '',
            uploadedAt: doc.createdAt || doc.uploadedAt || new Date().toISOString(),
            uploadedBy: doc.uploadedBy || '',
            currentVersion: doc.currentVersion || 1,
          }));
          this.detailedDocuments.set(mapped);
          this.loadingDocuments.set(false);
        },
        error: (err) => {
          console.error('Failed to load detailed documents:', err);
          this.detailedDocuments.set([]);
          this.loadingDocuments.set(false);
        },
      });
  }

  openUploadDialog(): void {
    const req = this.request();
    if (!req) return;

    const dialogRef = this.dialog.open(DocumentUploadComponent, {
      width: '560px',
      data: { requestId: req.id } as DocumentUploadDialogData,
    });

    dialogRef.afterClosed()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((result) => {
        if (result) {
          // Reload documents after successful upload
          this.loadDetailedDocuments(req.id);
        }
      });
  }

  submitRequest(): void {
    const req = this.request();
    if (!req) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Submit Request',
        message:
          'Are you sure you want to submit this request? Once submitted, you cannot make changes until the review is complete.',
        confirmText: 'Submit',
        confirmColor: 'primary',
      },
    });

    dialogRef.afterClosed()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((confirmed) => {
        if (confirmed) {
          this.submitting.set(true);
          this.requestService.submitRequest(req.id)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
              next: () => {
                this.notification.success('Request submitted successfully');
                this.loadRequest();
                this.submitting.set(false);
              },
              error: () => {
                this.submitting.set(false);
              },
            });
        }
      });
  }

  cancelRequest(): void {
    const req = this.request();
    if (!req) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Cancel Request',
        message: 'Are you sure you want to cancel this request? This action cannot be undone.',
        confirmText: 'Cancel Request',
        confirmColor: 'warn',
      },
    });

    dialogRef.afterClosed()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((confirmed) => {
        if (confirmed) {
          this.requestService.cancelRequest(req.id)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
              next: () => {
                this.notification.success('Request cancelled');
                this.loadRequest();
              },
              error: (err) => {
                this.notification.error('Operation failed. Please try again.');
                console.error('Error:', err);
              },
            });
        }
      });
  }

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

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

  getMetadataKeys(metadata: Record<string, any> | undefined): string[] {
    return metadata ? Object.keys(metadata) : [];
  }

  hasMetadata(metadata: Record<string, any> | undefined): boolean {
    return metadata ? Object.keys(metadata).length > 0 : false;
  }

  formatMetadataKey(key: string): string {
    // Convert camelCase to Title Case
    return key
      .replace(/([A-Z])/g, ' $1')
      .replace(/^./, (str) => str.toUpperCase())
      .trim();
  }

  formatDepartmentId(deptId: string): string {
    // Convert department IDs like "FIRE_DEPT" to "Fire Department"
    return deptId
      .replace(/_/g, ' ')
      .toLowerCase()
      .replace(/\b\w/g, (c) => c.toUpperCase())
      .replace(/Dept/g, 'Department');
  }
}
