import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ReportsService } from '../../core/services/reports.service';
import { DashboardResponse, ReportFilters } from '../../core/models/reports.models';

@Component({
  selector: 'app-dashboard-view',
  templateUrl: './dashboard-view.component.html',
  styleUrls: ['./dashboard-view.component.scss']
})
export class DashboardViewComponent implements OnInit {

  public dashboardType: string = 'general';
  public isLoadingDetails = false;
  public generatedBadges: any[] = [];

  // Data properties for different dashboard types
  public recentActivities: any[] = [];
  public projectStatuses: any[] = [];
  public activeTeamMembers: any[] = [];
  public teamWorkload: any[] = [];
  public performanceMetrics: any[] = [];
  public recentReports: any[] = [];
  public systemAlerts: any[] = [];
  public upcomingTasks: any[] = [];
  public calendarEvents: any[] = [];
  public financeKPIs: any[] = [];
  public recentTransactions: any[] = [];
  public topClients: any[] = [];
  public kanbanColumns: any[] = [];
  public upcomingMilestones: any[] = [];

  // Reporting dashboard data
  public reportsDashboard: DashboardResponse | null = null;
  public reportingError: string | null = null;

  constructor(
    private route: ActivatedRoute,
    private reportsService: ReportsService
  ) { }

  ngOnInit(): void {
    // Détecter le type de dashboard depuis l'URL
    const urlSegments = this.route.snapshot.url;
    if (urlSegments.length > 0) {
      this.dashboardType = urlSegments[urlSegments.length - 1].path;
    }

    console.log('📊 Dashboard type:', this.dashboardType);

    this.loadDashboardData();
    this.generateBadges();
  }

  loadDashboardData(): void {
    this.isLoadingDetails = true;

    if (this.dashboardType === 'reporting') {
      this.loadReportingDashboard();
    } else {
      // Simulate loading delay for other dashboards
      setTimeout(() => {
        this.initializeDashboardData();
        this.isLoadingDetails = false;
      }, 1000);
    }
  }

  async loadReportingDashboard(): Promise<void> {
    try {
      const today = new Date();
      const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

      const filters: ReportFilters = {
        date_from: firstDayOfMonth.toISOString().split('T')[0],
        date_to: today.toISOString().split('T')[0]
      };

      this.reportsDashboard = await this.reportsService.getDashboard(filters).toPromise();
      this.reportingError = null;
      console.log('✅ Reporting dashboard chargé:', this.reportsDashboard);
    } catch (error: any) {
      console.error('❌ Erreur chargement reporting:', error);
      this.reportingError = error.message || 'Erreur de chargement';
    } finally {
      this.isLoadingDetails = false;
    }
  }

  private initializeDashboardData(): void {
    // Initialize data based on dashboard type
    this.recentActivities = [
      { user: 'Marie Dupont', action: 'a créé un nouveau projet', time: 'il y a 2 min', initials: 'MD', color: '#206bc4' },
      { user: 'Jean Martin', action: 'a mis à jour le rapport', time: 'il y a 5 min', initials: 'JM', color: '#79a6dc' },
      { user: 'Sophie Bernard', action: 'a terminé une tâche', time: 'il y a 10 min', initials: 'SB', color: '#f59f00' }
    ];

    this.projectStatuses = [
      { label: 'En cours', count: 12, color: '#206bc4' },
      { label: 'Terminés', count: 8, color: '#28a745' },
      { label: 'En attente', count: 4, color: '#ffc107' },
      { label: 'Annulés', count: 2, color: '#dc3545' }
    ];

    this.activeTeamMembers = [
      { name: 'Marie Dupont', email: 'marie@example.com', role: 'Chef de projet', completedTasks: 8, totalTasks: 10, score: 85, initials: 'MD', color: '#206bc4' },
      { name: 'Jean Martin', email: 'jean@example.com', role: 'Développeur', completedTasks: 12, totalTasks: 15, score: 92, initials: 'JM', color: '#79a6dc' },
      { name: 'Sophie Bernard', email: 'sophie@example.com', role: 'Designer', completedTasks: 6, totalTasks: 8, score: 78, initials: 'SB', color: '#f59f00' }
    ];

    this.teamWorkload = [
      { name: 'Marie Dupont', role: 'Chef de projet', workload: 85, activeProjects: 3, initials: 'MD', color: '#206bc4' },
      { name: 'Jean Martin', role: 'Développeur', workload: 92, activeProjects: 4, initials: 'JM', color: '#79a6dc' },
      { name: 'Sophie Bernard', role: 'Designer', workload: 78, activeProjects: 2, initials: 'SB', color: '#f59f00' }
    ];

    this.performanceMetrics = [
      { title: 'Taux de réussite', value: '94%' },
      { title: 'Projets livrés', value: '28' },
      { title: 'Satisfaction client', value: '4.8/5' },
      { title: 'Temps moyen', value: '12j' }
    ];

    this.recentReports = [
      { title: 'Rapport mensuel', description: 'Analyse des performances', date: '15/01', status: 'completed', color: '#28a745' },
      { title: 'Audit qualité', description: 'Contrôle des processus', date: '12/01', status: 'pending', color: '#ffc107' },
      { title: 'Bilan financier', description: 'Résultats trimestriels', date: '10/01', status: 'draft', color: '#6c757d' }
    ];

    this.systemAlerts = [
      { message: 'Utilisation CPU élevée', threshold: '80%', currentValue: '92%', isExceeded: true, color: '#dc3545' },
      { message: 'Espace disque faible', threshold: '90%', currentValue: '75%', isExceeded: false, color: '#28a745' },
      { message: 'Connexions simultanées', threshold: '1000', currentValue: '1250', isExceeded: true, color: '#dc3545' }
    ];

    this.upcomingTasks = [
      { title: 'Révision du code', description: 'Module authentification', priority: 'high', completed: false },
      { title: 'Tests unitaires', description: 'Composants dashboard', priority: 'medium', completed: false },
      { title: 'Documentation API', description: 'Endpoints utilisateurs', priority: 'low', completed: true }
    ];

    this.calendarEvents = [
      { title: 'Réunion équipe', date: new Date(), color: '#206bc4' },
      { title: 'Présentation client', date: new Date(Date.now() + 86400000), color: '#f59f00' },
      { title: 'Formation Angular', date: new Date(Date.now() + 172800000), color: '#28a745' }
    ];

    this.financeKPIs = [
      { title: 'Chiffre d\'affaires', value: '€125,430' },
      { title: 'Bénéfices', value: '€32,150' },
      { title: 'Coûts', value: '€93,280' },
      { title: 'ROI', value: '34.5%' }
    ];

    this.recentTransactions = [
      { date: '15/01/2024', description: 'Paiement client ABC', category: 'revenue', amount: 5000, status: 'completed' },
      { date: '14/01/2024', description: 'Achat matériel', category: 'expense', amount: -1200, status: 'completed' },
      { date: '13/01/2024', description: 'Facture hébergement', category: 'expense', amount: -89, status: 'pending' }
    ];

    this.topClients = [
      { name: 'Entreprise ABC', location: 'Paris', revenue: 25000, trend: 'up' },
      { name: 'Société XYZ', location: 'Lyon', revenue: 18500, trend: 'up' },
      { name: 'Groupe DEF', location: 'Marseille', revenue: 12300, trend: 'down' }
    ];

    this.kanbanColumns = [
      { 
        title: 'À faire', 
        count: 5, 
        color: '#6c757d',
        projects: [
          { title: 'Nouveau site web', assignee: 'Marie D.', priority: 'high' },
          { title: 'App mobile', assignee: 'Jean M.', priority: 'medium' }
        ]
      },
      { 
        title: 'En cours', 
        count: 3, 
        color: '#206bc4',
        projects: [
          { title: 'Dashboard admin', assignee: 'Sophie B.', priority: 'high' }
        ]
      },
      { 
        title: 'Test', 
        count: 2, 
        color: '#f59f00',
        projects: [
          { title: 'API REST', assignee: 'Paul L.', priority: 'medium' }
        ]
      },
      { 
        title: 'Terminé', 
        count: 8, 
        color: '#28a745',
        projects: [
          { title: 'Site vitrine', assignee: 'Marie D.', priority: 'low' }
        ]
      }
    ];

    this.upcomingMilestones = [
      { title: 'Livraison v2.0', project: 'App Mobile', assignee: 'Jean M.', date: new Date(), status: 'on-track', color: '#206bc4' },
      { title: 'Tests finaux', project: 'Dashboard', assignee: 'Sophie B.', date: new Date(Date.now() + 86400000), status: 'at-risk', color: '#f59f00' },
      { title: 'Déploiement', project: 'API REST', assignee: 'Paul L.', date: new Date(Date.now() + 172800000), status: 'completed', color: '#28a745' }
    ];
  }

  generateBadges(): void {
    // Generate badges based on dashboard type
    switch (this.dashboardType) {
      case 'general':
        this.generatedBadges = [
          { title: 'Projets Actifs', value: 12, trend: 'up', variation: 8 },
          { title: 'Équipe Active', value: 8, trend: 'stable', variation: 0 },
          { title: 'Tâches Terminées', value: 45, trend: 'up', variation: 12 },
          { title: 'Performance', value: '94%', trend: 'up', variation: 3 }
        ];
        break;
      case 'finance':
        this.generatedBadges = [
          { title: 'Revenus', value: '€125,430', trend: 'up', variation: 15 },
          { title: 'Dépenses', value: '€93,280', trend: 'down', variation: 5 },
          { title: 'Bénéfices', value: '€32,150', trend: 'up', variation: 22 },
          { title: 'ROI', value: '34.5%', trend: 'up', variation: 8 }
        ];
        break;
      case 'projects':
        this.generatedBadges = [
          { title: 'En Cours', value: 5, trend: 'up', variation: 2 },
          { title: 'Terminés', value: 8, trend: 'up', variation: 3 },
          { title: 'En Retard', value: 1, trend: 'down', variation: 1 },
          { title: 'Équipe', value: 12, trend: 'stable', variation: 0 }
        ];
        break;
      case 'reporting':
        this.generatedBadges = [
          { title: 'Rapports', value: 24, trend: 'up', variation: 6 },
          { title: 'Alertes', value: 3, trend: 'down', variation: 2 },
          { title: 'Métriques', value: 18, trend: 'up', variation: 4 },
          { title: 'Analyses', value: 7, trend: 'up', variation: 1 }
        ];
        break;
      default:
        this.generatedBadges = [];
    }
  }

  // Utility methods
  getDashboardTitle(): string {
    switch (this.dashboardType) {
      case 'general': return 'Dashboard Général';
      case 'finance': return 'Dashboard Finance';
      case 'projects': return 'Dashboard Projets';
      case 'reporting': return 'Dashboard Reporting';
      default: return 'Dashboard';
    }
  }

  getDashboardPretitle(): string {
    return 'Vue d\'ensemble';
  }

  getFormattedValue(badge: any): string {
    return badge.value.toString();
  }

  trackByBadge(index: number, badge: any): string {
    return badge.title + badge.value;
  }

  refreshDashboard(): void {
    this.loadDashboardData();
    this.generateBadges();
  }

  getPerformanceBadgeClass(score: number): string {
    if (score >= 90) return 'bg-success';
    if (score >= 75) return 'bg-warning';
    return 'bg-danger';
  }

  getTransactionCategoryClass(category: string): string {
    switch (category) {
      case 'revenue': return 'text-success';
      case 'expense': return 'text-danger';
      default: return 'text-muted';
    }
  }

  getStatusBadgeClass(status: string): string {
    switch (status) {
      case 'completed': return 'bg-success';
      case 'pending': return 'bg-warning';
      case 'draft': return 'bg-secondary';
      case 'on-track': return 'bg-success';
      case 'at-risk': return 'bg-warning';
      default: return 'bg-secondary';
    }
  }

  getStatusLabel(status: string): string {
    switch (status) {
      case 'completed': return 'Terminé';
      case 'pending': return 'En attente';
      case 'draft': return 'Brouillon';
      default: return status;
    }
  }

  getPriorityBadgeClass(priority: string): string {
    switch (priority) {
      case 'high': return 'bg-danger';
      case 'medium': return 'bg-warning';
      case 'low': return 'bg-success';
      default: return 'bg-secondary';
    }
  }

  getWorkloadColor(workload: number): string {
    if (workload >= 90) return '#dc3545';
    if (workload >= 75) return '#ffc107';
    return '#28a745';
  }

  // Méthodes pour le dashboard reporting
  getReportKeys(): string[] {
    if (!this.reportsDashboard?.reports) return [];
    return Object.keys(this.reportsDashboard.reports);
  }

  getReportTitleFromKey(key: string): string {
    const titles: { [key: string]: string } = {
      'banques_mouvements': 'Mouvements Bancaires',
      'financial_requests_mouvements': 'Demandes Financières',
      'creditlimits': 'Limites de Crédit',
      'soldesbmp_soldes': 'Soldes BMP',
      'bmps_etatsdeventes': 'BMP États de Ventes',
      'bspdetails_etatsdeventes': 'BSP Détails États de Ventes'
    };
    return titles[key] || key;
  }

  getReportPercentage(key: string): number {
    if (!this.reportsDashboard?.reports) return 0;
    const reports = this.reportsDashboard.reports as any;
    const report = reports[key];
    return report?.matched_percentage || 0;
  }

  getReportStatus(key: string): 'good' | 'warning' | 'critical' {
    if (!this.reportsDashboard?.reports) return 'critical';
    const reports = this.reportsDashboard.reports as any;
    const report = reports[key];
    return report?.health_status || 'critical';
  }

  getReportStatusLabel(key: string): string {
    const status = this.getReportStatus(key);
    switch (status) {
      case 'good': return 'Excellent';
      case 'warning': return 'Attention';
      case 'critical': return 'Critique';
      default: return '';
    }
  }

  getReportTotalValue(key: string): number {
    if (!this.reportsDashboard?.reports) return 0;
    const reports = this.reportsDashboard.reports as any;
    const report = reports[key];

    // Déterminer le champ 'total' selon le type de rapport
    if (key === 'banques_mouvements') return report?.total_depots || 0;
    if (key === 'financial_requests_mouvements') return report?.total_financial_requests || 0;
    if (key === 'creditlimits') return report?.total_creditlimits || 0;
    if (key === 'soldesbmp_soldes') return report?.total_soldesbmp || 0;
    if (key === 'bmps_etatsdeventes') return report?.total_bmps || 0;
    if (key === 'bspdetails_etatsdeventes') return report?.total_bspdetails || 0;

    return 0;
  }

  getReportMatchedValue(key: string): number {
    if (!this.reportsDashboard?.reports) return 0;
    const reports = this.reportsDashboard.reports as any;
    const report = reports[key];

    // Déterminer le champ 'matched' selon le type de rapport
    if (key === 'banques_mouvements') return report?.matched || 0;
    if (key === 'financial_requests_mouvements') return report?.with_mouvement || 0;
    if (key === 'creditlimits') return report?.with_mouvement || 0;
    if (key === 'soldesbmp_soldes') return report?.with_solde || 0;
    if (key === 'bmps_etatsdeventes') return report?.with_etatsdevente || 0;
    if (key === 'bspdetails_etatsdeventes') return report?.with_etatsdevente || 0;

    return 0;
  }

  getReportUnmatchedValue(key: string): number {
    if (!this.reportsDashboard?.reports) return 0;
    const reports = this.reportsDashboard.reports as any;
    const report = reports[key];

    // Déterminer le champ 'unmatched' selon le type de rapport
    if (key === 'banques_mouvements') return report?.unmatched || 0;
    if (key === 'financial_requests_mouvements') return report?.without_mouvement || 0;
    if (key === 'creditlimits') return report?.without_mouvement || 0;
    if (key === 'soldesbmp_soldes') return report?.without_solde || 0;
    if (key === 'bmps_etatsdeventes') return report?.without_etatsdevente || 0;
    if (key === 'bspdetails_etatsdeventes') return report?.without_etatsdevente || 0;

    return 0;
  }
}