import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { ReportsService } from '../../../../../core/services/reports.service';
import {
  ReportFilters,
  ReportDetail,
  Alert,
  AccountBreakdown
} from '../../../../../core/models/reports.models';

@Component({
  selector: 'app-report-detail-panel',
  templateUrl: './report-detail-panel.component.html',
  styleUrls: ['./report-detail-panel.component.scss']
})
export class ReportDetailPanelComponent implements OnChanges {
  @Input() visible = false;
  @Input() reportType: string | null = null;
  @Input() reportTitle = '';
  @Input() filters!: ReportFilters;

  @Output() visibleChange = new EventEmitter<boolean>();
  @Output() exportRequested = new EventEmitter<{ reportType: string; format: 'csv' | 'excel' }>();

  isLoading = false;
  error: string | null = null;
  reportDetail: ReportDetail | null = null;

  constructor(
    private reportsService: ReportsService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['visible'] && this.visible && this.reportType) {
      this.loadReport();
    }
  }

  async loadReport(): Promise<void> {
    if (!this.reportType || !this.filters) return;

    this.isLoading = true;
    this.error = null;
    this.reportDetail = null;
    this.cdr.markForCheck();

    try {
      this.reportDetail = await this.reportsService
        .getReportDetail(this.reportType, this.filters)
        .toPromise() || null;
      console.log('📋 Rapport détaillé chargé:', this.reportDetail);
    } catch (err: any) {
      console.error('❌ Erreur chargement rapport détaillé:', err);
      if (err.status) {
        this.error = `Erreur serveur ${err.status}: ${err.error?.detail || err.error?.message || err.statusText || 'Erreur interne'}`;
      } else {
        this.error = err.message || 'Erreur lors du chargement du rapport';
      }
    } finally {
      this.isLoading = false;
      this.cdr.markForCheck();
    }
  }

  close(): void {
    this.visible = false;
    this.visibleChange.emit(false);
  }

  onExport(format: 'csv' | 'excel'): void {
    if (this.reportType) {
      this.exportRequested.emit({ reportType: this.reportType, format });
    }
  }

  getAlertBadgeClass(severity: string): string {
    switch (severity) {
      case 'critical': return 'bg-red';
      case 'warning': return 'bg-yellow';
      case 'info': return 'bg-green';
      default: return 'bg-blue';
    }
  }

  getDetailItems(): any[] {
    if (!this.reportDetail?.details) return [];
    const details = this.reportDetail.details;
    const firstArrayKey = Object.keys(details).find(k => Array.isArray(details[k]));
    return firstArrayKey ? details[firstArrayKey] : [];
  }

  getDetailColumns(): string[] {
    const items = this.getDetailItems();
    if (items.length === 0) return [];
    return Object.keys(items[0]).filter(k => !['id', 'uuid'].includes(k));
  }

  formatColumnHeader(key: string): string {
    return key
      .replace(/_/g, ' ')
      .replace(/\b\w/g, c => c.toUpperCase());
  }

  formatCellValue(value: any): string {
    if (value === null || value === undefined) return '-';
    if (typeof value === 'number') {
      return new Intl.NumberFormat('fr-FR').format(value);
    }
    return String(value);
  }

  getAccountBreakdowns(): AccountBreakdown[] {
    return this.reportDetail?.charts?.by_account || [];
  }
}
