/**
 * CodesPanel - Panneau d'affichage des codes proposés
 * 
 * Responsabilités:
 * - Afficher DP, DR, DAS, CCAM avec badges de confiance
 * - Gérer les filtres (type, confiance, sans preuves)
 * - Gérer la sélection de code
 * - Afficher l'indicateur de complétude
 * 
 * Validates: Requirements 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7
 */
class CodesPanel {
  constructor(stateManager) {
    this.stateManager = stateManager;
    this.container = document.getElementById('codes-list');
    this.filtersContainer = document.getElementById('codes-filters');
    
    // S'abonner aux changements d'état
    this.stateManager.on('stayChanged', (stay) => this.render(stay));
    this.stateManager.on('filtersChanged', () => this.render(this.stateManager.getCurrentStay()));
    this.stateManager.on('codeSelected', (code) => this.updateSelection(code));
    
    this.renderFilters();
  }

  /**
   * Calculer l'indicateur de complétude du codage
   * Validates: Requirements 3.7
   */
  calculateCompleteness(codes) {
    const allCodes = [];
    if (codes.dp) allCodes.push(codes.dp);
    if (codes.dr) allCodes.push(codes.dr);
    if (codes.das) allCodes.push(...codes.das);
    if (codes.ccam) allCodes.push(...codes.ccam);
    
    if (allCodes.length === 0) return 0;
    
    const codesWithEvidence = allCodes.filter(code => 
      code.evidence && code.evidence.length > 0
    ).length;
    
    return Math.round((codesWithEvidence / allCodes.length) * 100);
  }

  /**
   * Obtenir la classe CSS du badge de confiance
   * Validates: Requirements 3.2, 3.3, 3.4
   */
  getConfidenceClass(confidence) {
    if (confidence >= 0.8) return 'confidence-high';
    if (confidence >= 0.5) return 'confidence-medium';
    return 'confidence-low';
  }

  /**
   * Filtrer les codes selon les filtres actifs
   */
  filterCodes(codes) {
    const filters = this.stateManager.getFilters();
    let filtered = { dp: codes.dp, dr: codes.dr, das: [...(codes.das || [])], ccam: [...(codes.ccam || [])] };
    
    // Filtre par type de code
    if (filters.codeType.length > 0) {
      if (!filters.codeType.includes('dp')) filtered.dp = null;
      if (!filters.codeType.includes('dr')) filtered.dr = null;
      if (!filters.codeType.includes('das')) filtered.das = [];
      if (!filters.codeType.includes('ccam')) filtered.ccam = [];
    }
    
    // Filtre par niveau de confiance
    if (filters.confidenceLevel.length > 0) {
      const matchesConfidence = (code) => {
        if (!code) return false;
        if (filters.confidenceLevel.includes('high') && code.confidence >= 0.8) return true;
        if (filters.confidenceLevel.includes('medium') && code.confidence >= 0.5 && code.confidence < 0.8) return true;
        if (filters.confidenceLevel.includes('low') && code.confidence < 0.5) return true;
        return false;
      };
      
      if (filtered.dp && !matchesConfidence(filtered.dp)) filtered.dp = null;
      if (filtered.dr && !matchesConfidence(filtered.dr)) filtered.dr = null;
      filtered.das = filtered.das.filter(matchesConfidence);
      filtered.ccam = filtered.ccam.filter(matchesConfidence);
    }
    
    // Filtre sans preuves
    if (filters.withoutEvidence) {
      const hasNoEvidence = (code) => !code.evidence || code.evidence.length === 0;
      if (filtered.dp && !hasNoEvidence(filtered.dp)) filtered.dp = null;
      if (filtered.dr && !hasNoEvidence(filtered.dr)) filtered.dr = null;
      filtered.das = filtered.das.filter(hasNoEvidence);
      filtered.ccam = filtered.ccam.filter(hasNoEvidence);
    }
    
    return filtered;
  }

  /**
   * Créer le HTML d'un code
   */
  createCodeHTML(title, code, type) {
    if (!code) return '';
    
    const confidenceClass = this.getConfidenceClass(code.confidence);
    const confidencePercent = Math.round(code.confidence * 100);
    const evidenceCount = code.evidence ? code.evidence.length : 0;
    const selectedCode = this.stateManager.getSelectedCode();
    const isSelected = selectedCode && selectedCode.code === code.code;
    
    // Afficher le reasoning si disponible
    const reasoningHTML = code.reasoning ? `
      <div class="code-reasoning">
        💡 ${this.escapeHTML(code.reasoning)}
      </div>
    ` : '';
    
    // Afficher un aperçu des preuves
    let evidencePreviewHTML = '';
    if (code.evidence && code.evidence.length > 0) {
      const firstEvidence = code.evidence[0];
      evidencePreviewHTML = `
        <div class="code-evidence-preview">
          📄 "${this.escapeHTML(firstEvidence.text.substring(0, 80))}${firstEvidence.text.length > 80 ? '...' : ''}"
        </div>
      `;
    }
    
    return `
      <div class="code-item ${isSelected ? 'selected' : ''}" 
           data-code="${code.code}" 
           data-type="${type}"
           onclick="window.codesPanel.selectCode('${code.code}', '${type}')">
        <div class="code-header">
          <span class="code-title">${title}: ${code.code}</span>
          <span class="confidence-badge ${confidenceClass}">
            ${confidencePercent}%
          </span>
        </div>
        <div class="code-label">${this.escapeHTML(code.label)}</div>
        ${reasoningHTML}
        ${evidencePreviewHTML}
        <div class="code-evidence-count">
          📄 ${evidenceCount} preuve${evidenceCount > 1 ? 's' : ''}
        </div>
      </div>
    `;
  }
  
  /**
   * Échapper le HTML
   */
  escapeHTML(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  /**
   * Rendre le panneau des codes
   */
  render(stay) {
    console.log('CodesPanel.render() called with stay:', stay);
    
    if (!stay || !stay.codes) {
      console.log('No stay or no codes, showing empty message');
      this.container.innerHTML = '<p class="text-center" style="color: #718096; padding: 40px;">Aucun code disponible</p>';
      return;
    }
    
    console.log('Stay codes:', stay.codes);
    console.log('Current filters:', this.stateManager.getFilters());
    
    const codes = this.filterCodes(stay.codes);
    console.log('Filtered codes:', codes);
    
    const completeness = this.calculateCompleteness(stay.codes);
    
    let html = `
      <div class="completeness-indicator">
        <div class="completeness-label">Complétude du codage</div>
        <div class="completeness-bar">
          <div class="completeness-fill" style="width: ${completeness}%"></div>
        </div>
        <div class="completeness-value">${completeness}%</div>
      </div>
    `;
    
    // DP
    if (codes.dp) {
      html += this.createCodeHTML('DP - Diagnostic Principal', codes.dp, 'dp');
    }
    
    // DR
    if (codes.dr) {
      html += this.createCodeHTML('DR - Diagnostic Relié', codes.dr, 'dr');
    }
    
    // DAS
    if (codes.das && codes.das.length > 0) {
      codes.das.forEach((code, index) => {
        html += this.createCodeHTML(`DAS ${index + 1}`, code, 'das');
      });
    }
    
    // CCAM
    if (codes.ccam && codes.ccam.length > 0) {
      codes.ccam.forEach((code, index) => {
        html += this.createCodeHTML(`CCAM ${index + 1}`, code, 'ccam');
      });
    }
    
    if (!codes.dp && !codes.dr && codes.das.length === 0 && codes.ccam.length === 0) {
      html += '<p class="text-center" style="color: #718096; padding: 20px;">Aucun code ne correspond aux filtres</p>';
    }
    
    this.container.innerHTML = html;
  }

  /**
   * Rendre les filtres
   */
  renderFilters() {
    const filters = this.stateManager.getFilters();
    
    this.filtersContainer.innerHTML = `
      <div class="filters-section">
        <div class="filter-group">
          <label class="filter-label">Type de code:</label>
          <div class="filter-options">
            <label class="filter-checkbox">
              <input type="checkbox" value="dp" ${filters.codeType.includes('dp') ? 'checked' : ''} 
                     onchange="window.codesPanel.toggleFilter('codeType', 'dp')">
              DP
            </label>
            <label class="filter-checkbox">
              <input type="checkbox" value="dr" ${filters.codeType.includes('dr') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('codeType', 'dr')">
              DR
            </label>
            <label class="filter-checkbox">
              <input type="checkbox" value="das" ${filters.codeType.includes('das') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('codeType', 'das')">
              DAS
            </label>
            <label class="filter-checkbox">
              <input type="checkbox" value="ccam" ${filters.codeType.includes('ccam') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('codeType', 'ccam')">
              CCAM
            </label>
          </div>
        </div>
        
        <div class="filter-group">
          <label class="filter-label">Confiance:</label>
          <div class="filter-options">
            <label class="filter-checkbox">
              <input type="checkbox" value="high" ${filters.confidenceLevel.includes('high') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('confidenceLevel', 'high')">
              Élevée (≥80%)
            </label>
            <label class="filter-checkbox">
              <input type="checkbox" value="medium" ${filters.confidenceLevel.includes('medium') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('confidenceLevel', 'medium')">
              Moyenne (50-80%)
            </label>
            <label class="filter-checkbox">
              <input type="checkbox" value="low" ${filters.confidenceLevel.includes('low') ? 'checked' : ''}
                     onchange="window.codesPanel.toggleFilter('confidenceLevel', 'low')">
              Faible (<50%)
            </label>
          </div>
        </div>
        
        <div class="filter-group">
          <label class="filter-checkbox">
            <input type="checkbox" ${filters.withoutEvidence ? 'checked' : ''}
                   onchange="window.codesPanel.toggleWithoutEvidence()">
            Sans preuves uniquement
          </label>
        </div>
        
        <button class="btn btn-secondary btn-small" onclick="window.codesPanel.resetFilters()">
          Réinitialiser
        </button>
      </div>
    `;
  }

  /**
   * Basculer un filtre
   */
  toggleFilter(filterType, value) {
    const filters = this.stateManager.getFilters();
    const array = filters[filterType];
    const index = array.indexOf(value);
    
    if (index > -1) {
      array.splice(index, 1);
    } else {
      array.push(value);
    }
    
    this.stateManager.setFilters({ [filterType]: array });
  }

  /**
   * Basculer le filtre "sans preuves"
   */
  toggleWithoutEvidence() {
    const filters = this.stateManager.getFilters();
    this.stateManager.setFilters({ withoutEvidence: !filters.withoutEvidence });
  }

  /**
   * Réinitialiser les filtres
   */
  resetFilters() {
    this.stateManager.setFilters({
      codeType: [],
      confidenceLevel: [],
      withoutEvidence: false
    });
    this.renderFilters();
  }

  /**
   * Sélectionner un code
   * Validates: Requirements 3.6
   */
  selectCode(codeValue, type) {
    const stay = this.stateManager.getCurrentStay();
    if (!stay) return;
    
    let selectedCode = null;
    
    if (type === 'dp') {
      selectedCode = stay.codes.dp;
    } else if (type === 'dr') {
      selectedCode = stay.codes.dr;
    } else if (type === 'das') {
      selectedCode = stay.codes.das.find(c => c.code === codeValue);
    } else if (type === 'ccam') {
      selectedCode = stay.codes.ccam.find(c => c.code === codeValue);
    }
    
    if (selectedCode) {
      this.stateManager.setSelectedCode({ ...selectedCode, type });
    }
  }

  /**
   * Mettre à jour la sélection visuelle
   */
  updateSelection(code) {
    // Retirer la sélection précédente
    const previousSelected = this.container.querySelector('.code-item.selected');
    if (previousSelected) {
      previousSelected.classList.remove('selected');
    }
    
    // Ajouter la nouvelle sélection
    if (code) {
      const codeElement = this.container.querySelector(`[data-code="${code.code}"]`);
      if (codeElement) {
        codeElement.classList.add('selected');
      }
    }
  }
}

// Export pour utilisation dans d'autres modules
if (typeof module !== 'undefined' && module.exports) {
  module.exports = CodesPanel;
}
