import { Component, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';

// 📊 Interface para dados de volumes transportados
export interface VolumeData {
  totalVolumes: number;
  averagePerVehicle: number;
  efficiency: number;
  concluded: number;
  active: number;
  pending: number;
  delayed: number;
  changePercentage: number;
  trend: 'up' | 'down' | 'stable';
  // ✨ NOVO: Breakdown por tipo de rota
  concludedByType?: {
    firstMile: number;
    lineHaul: number;
    lastMile: number;
    custom: number;
  };
  activeByType?: {
    firstMile: number;
    lineHaul: number;
    lastMile: number;
    custom: number;
  };
  pendingByType?: {
    firstMile: number;
    lineHaul: number;
    lastMile: number;
    custom: number;
  };
  delayedByType?: {
    firstMile: number;
    lineHaul: number;
    lastMile: number;
    custom: number;
  };
  priority?: number;
  hasAmbulance?: number;
}

@Component({
  selector: 'app-volumes-transported-card',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="volumes-card">
      <!-- Header -->
      <div class="card-header">
        <div class="header-left">
          <div class="icon-container">
            <i class="fas fa-truck-loading"></i>
          </div>
          <div class="header-info">
            <h3>Volumes Transportados</h3>
            <p class="total-volumes">{{ formatNumber(data.totalVolumes) }} volumes totais</p>
          </div>
        </div>
        <div class="trend-indicator" [class]="getTrendClass()">
          <i class="fas" [class.fa-arrow-up]="data.trend === 'up'" 
                        [class.fa-arrow-down]="data.trend === 'down'"
                        [class.fa-minus]="data.trend === 'stable'"></i>
          <span>{{ data.changePercentage.toFixed(1) }}%</span>
        </div>
      </div>

      <!-- Metrics Row -->
      <div class="metrics-row">
        <div class="metric-item">
          <label>Média por Veículo</label>
          <span class="metric-value">{{ data.averagePerVehicle.toFixed(1) }}</span>
        </div>
        <div class="metric-item">
          <label>Eficiência</label>
          <span class="metric-value">{{ data.efficiency.toFixed(1) }}%</span>
        </div>
        <div class="metric-item">
          <label>
            <i class="fas fa-exclamation-triangle priority-icon"></i>
            Prioridade
          </label>
          <div class="metric-value priority-value">
            <span class="priority-badge" *ngIf="(data.priority || 0) > 0">
              <i class="fas fa-fire"></i>
              Alta
            </span>
            <span class="priority-count">{{ data.priority || 0 }}</span>
          </div>
        </div>
        <div class="metric-item">
          <label>
            <i class="fas fa-plus-circle help-icon"></i>
            Help
          </label>
          <div class="metric-value help-value">
            <span class="help-badge" *ngIf="(data.hasAmbulance || 0) > 0">
              <i class="fas fa-ambulance"></i>
              Acionados
            </span>
            <span class="help-count">{{ data.hasAmbulance || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- Status Bars -->
      <div class="status-section">
        <div class="status-item concluded">
          <div class="status-header">
            <label>Concluídos</label>
            <span class="status-value">{{ formatNumber(data.concluded) }}</span>
          </div>
          <div class="status-bar">
            <!-- ✨ NOVO: Barra segmentada por tipo de rota -->
            <div class="status-fill-segmented" [style.width.%]="100">
              <div 
                *ngIf="data.concludedByType?.firstMile" 
                class="segment first-mile" 
                [style.width.%]="getTypePercentage('firstMile', 'concluded')"
                [title]="'First Mile: ' + (data.concludedByType?.firstMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.concludedByType?.lineHaul" 
                class="segment line-haul" 
                [style.width.%]="getTypePercentage('lineHaul', 'concluded')"
                [title]="'Line Haul: ' + (data.concludedByType?.lineHaul || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.concludedByType?.lastMile" 
                class="segment last-mile" 
                [style.width.%]="getTypePercentage('lastMile', 'concluded')"
                [title]="'Last Mile: ' + (data.concludedByType?.lastMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.concludedByType?.custom" 
                class="segment custom" 
                [style.width.%]="getTypePercentage('custom', 'concluded')"
                [title]="'Custom: ' + (data.concludedByType?.custom || 0) + ' rotas'">
              </div>
            </div>
          </div>
          <!-- ✨ NOVO: Legenda dos tipos -->
          <div class="type-breakdown" *ngIf="data.concludedByType && hasAnyTypeData('concluded')">
            <div class="type-item" *ngIf="data.concludedByType.firstMile > 0">
              <div class="type-color first-mile"></div>
              <span class="type-label">First Mile</span>
              <span class="type-count">{{ data.concludedByType.firstMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.concludedByType.lineHaul > 0">
              <div class="type-color line-haul"></div>
              <span class="type-label">Line Haul</span>
              <span class="type-count">{{ data.concludedByType.lineHaul }}</span>
            </div>
            <div class="type-item" *ngIf="data.concludedByType.lastMile > 0">
              <div class="type-color last-mile"></div>
              <span class="type-label">Last Mile</span>
              <span class="type-count">{{ data.concludedByType.lastMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.concludedByType.custom > 0">
              <div class="type-color custom"></div>
              <span class="type-label">Custom</span>
              <span class="type-count">{{ data.concludedByType.custom }}</span>
            </div>
          </div>
        </div>

        <div class="status-item active">
          <div class="status-header">
            <label>Ativos</label>
            <span class="status-value">{{ formatNumber(data.active) }}</span>
          </div>
          <div class="status-bar">
            <!-- ✨ NOVO: Barra segmentada por tipo de rota -->
            <div class="status-fill-segmented" [style.width.%]="100">
              <div 
                *ngIf="data.activeByType?.firstMile" 
                class="segment first-mile" 
                [style.width.%]="getTypePercentage('firstMile', 'active')"
                [title]="'First Mile: ' + (data.activeByType?.firstMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.activeByType?.lineHaul" 
                class="segment line-haul" 
                [style.width.%]="getTypePercentage('lineHaul', 'active')"
                [title]="'Line Haul: ' + (data.activeByType?.lineHaul || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.activeByType?.lastMile" 
                class="segment last-mile" 
                [style.width.%]="getTypePercentage('lastMile', 'active')"
                [title]="'Last Mile: ' + (data.activeByType?.lastMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.activeByType?.custom" 
                class="segment custom" 
                [style.width.%]="getTypePercentage('custom', 'active')"
                [title]="'Custom: ' + (data.activeByType?.custom || 0) + ' rotas'">
              </div>
            </div>
          </div>
          <!-- ✨ NOVO: Legenda dos tipos -->
          <div class="type-breakdown" *ngIf="data.activeByType && hasAnyTypeData('active')">
            <div class="type-item" *ngIf="data.activeByType.firstMile > 0">
              <div class="type-color first-mile"></div>
              <span class="type-label">First Mile</span>
              <span class="type-count">{{ data.activeByType.firstMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.activeByType.lineHaul > 0">
              <div class="type-color line-haul"></div>
              <span class="type-label">Line Haul</span>
              <span class="type-count">{{ data.activeByType.lineHaul }}</span>
            </div>
            <div class="type-item" *ngIf="data.activeByType.lastMile > 0">
              <div class="type-color last-mile"></div>
              <span class="type-label">Last Mile</span>
              <span class="type-count">{{ data.activeByType.lastMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.activeByType.custom > 0">
              <div class="type-color custom"></div>
              <span class="type-label">Custom</span>
              <span class="type-count">{{ data.activeByType.custom }}</span>
            </div>
          </div>
        </div>

        <div class="status-item pending" *ngIf="data.pending > 0">
          <div class="status-header">
            <label>Pendentes</label>
            <span class="status-value">{{ formatNumber(data.pending) }}</span>
          </div>
          <div class="status-bar">
            <!-- ✨ NOVO: Barra segmentada por tipo de rota -->
            <div class="status-fill-segmented" [style.width.%]="100">
              <div 
                *ngIf="data.pendingByType?.firstMile" 
                class="segment first-mile" 
                [style.width.%]="getTypePercentage('firstMile', 'pending')"
                [title]="'First Mile: ' + (data.pendingByType?.firstMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.pendingByType?.lineHaul" 
                class="segment line-haul" 
                [style.width.%]="getTypePercentage('lineHaul', 'pending')"
                [title]="'Line Haul: ' + (data.pendingByType?.lineHaul || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.pendingByType?.lastMile" 
                class="segment last-mile" 
                [style.width.%]="getTypePercentage('lastMile', 'pending')"
                [title]="'Last Mile: ' + (data.pendingByType?.lastMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.pendingByType?.custom" 
                class="segment custom" 
                [style.width.%]="getTypePercentage('custom', 'pending')"
                [title]="'Custom: ' + (data.pendingByType?.custom || 0) + ' rotas'">
              </div>
            </div>
          </div>
          <!-- ✨ NOVO: Legenda dos tipos -->
          <div class="type-breakdown" *ngIf="data.pendingByType && hasAnyTypeData('pending')">
            <div class="type-item" *ngIf="data.pendingByType.firstMile > 0">
              <div class="type-color first-mile"></div>
              <span class="type-label">First Mile</span>
              <span class="type-count">{{ data.pendingByType.firstMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.pendingByType.lineHaul > 0">
              <div class="type-color line-haul"></div>
              <span class="type-label">Line Haul</span>
              <span class="type-count">{{ data.pendingByType.lineHaul }}</span>
            </div>
            <div class="type-item" *ngIf="data.pendingByType.lastMile > 0">
              <div class="type-color last-mile"></div>
              <span class="type-label">Last Mile</span>
              <span class="type-count">{{ data.pendingByType.lastMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.pendingByType.custom > 0">
              <div class="type-color custom"></div>
              <span class="type-label">Custom</span>
              <span class="type-count">{{ data.pendingByType.custom }}</span>
            </div>
          </div>
        </div>

        <div class="status-item delayed" *ngIf="data.delayed > 0">
          <div class="status-header">
            <label>Atrasados</label>
            <span class="status-value">{{ formatNumber(data.delayed) }}</span>
          </div>
          <div class="status-bar">
            <!-- ✨ NOVO: Barra segmentada por tipo de rota -->
            <div class="status-fill-segmented" [style.width.%]="100">
              <div 
                *ngIf="data.delayedByType?.firstMile" 
                class="segment first-mile" 
                [style.width.%]="getTypePercentage('firstMile', 'delayed')"
                [title]="'First Mile: ' + (data.delayedByType?.firstMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.delayedByType?.lineHaul" 
                class="segment line-haul" 
                [style.width.%]="getTypePercentage('lineHaul', 'delayed')"
                [title]="'Line Haul: ' + (data.delayedByType?.lineHaul || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.delayedByType?.lastMile" 
                class="segment last-mile" 
                [style.width.%]="getTypePercentage('lastMile', 'delayed')"
                [title]="'Last Mile: ' + (data.delayedByType?.lastMile || 0) + ' rotas'">
              </div>
              <div 
                *ngIf="data.delayedByType?.custom" 
                class="segment custom" 
                [style.width.%]="getTypePercentage('custom', 'delayed')"
                [title]="'Custom: ' + (data.delayedByType?.custom || 0) + ' rotas'">
              </div>
            </div>
          </div>
          <!-- ✨ NOVO: Legenda dos tipos -->
          <div class="type-breakdown" *ngIf="data.delayedByType && hasAnyTypeData('delayed')">
            <div class="type-item" *ngIf="data.delayedByType.firstMile > 0">
              <div class="type-color first-mile"></div>
              <span class="type-label">First Mile</span>
              <span class="type-count">{{ data.delayedByType.firstMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.delayedByType.lineHaul > 0">
              <div class="type-color line-haul"></div>
              <span class="type-label">Line Haul</span>
              <span class="type-count">{{ data.delayedByType.lineHaul }}</span>
            </div>
            <div class="type-item" *ngIf="data.delayedByType.lastMile > 0">
              <div class="type-color last-mile"></div>
              <span class="type-label">Last Mile</span>
              <span class="type-count">{{ data.delayedByType.lastMile }}</span>
            </div>
            <div class="type-item" *ngIf="data.delayedByType.custom > 0">
              <div class="type-color custom"></div>
              <span class="type-label">Custom</span>
              <span class="type-count">{{ data.delayedByType.custom }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styleUrl: './volumes-transported-card.component.scss'
})
export class VolumesTransportedCardComponent implements OnInit {
  @Input() data: VolumeData = {
    totalVolumes: 0,
    averagePerVehicle: 0,
    efficiency: 0,
    concluded: 0,
    active: 0,
    pending: 0,
    delayed: 0,
    changePercentage: 0,
    trend: 'stable',
    priority: 0,
    hasAmbulance: 0
  };

  ngOnInit() {
    // Componente inicializado
    console.log('🔍 DEBUG VolumeCard - Dados recebidos:', {
      data: this.data,
      concludedByType: this.data.concludedByType,
      hasTypeData: this.hasAnyTypeData('concluded')
    });
  }

  /**
   * 📊 Calcular percentual para as barras de status
   */
  getPercentage(value: number): number {
    if (this.data.totalVolumes === 0) return 0;
    return (value / this.data.totalVolumes) * 100;
  }

  /**
   * 🎨 Obter classe CSS para trend
   */
  getTrendClass(): string {
    return `trend-${this.data.trend}`;
  }

  /**
   * 🔢 Formatar números grandes
   */
  formatNumber(value: number): string {
    if (value >= 1000000) {
      return `${(value / 1000000).toFixed(1)}M`;
    } else if (value >= 1000) {
      return `${(value / 1000).toFixed(1)}K`;
    }
    return value.toString();
  }

  /**
   * ✨ NOVO: Calcular percentual de um tipo específico dentro de um status
   */
  getTypePercentage(type: 'firstMile' | 'lineHaul' | 'lastMile' | 'custom', status: 'concluded' | 'active' | 'pending' | 'delayed'): number {
    const statusData = this.data[`${status}ByType` as keyof VolumeData] as any;
    if (!statusData || !statusData[type]) {
      console.log(`🔍 DEBUG getTypePercentage - Sem dados para ${type}/${status}:`, { statusData, type, hasType: statusData?.[type] });
      return 0;
    }
    
    const totalForStatus = this.data[status];
    if (totalForStatus === 0) return 0;
    
    const percentage = (statusData[type] / totalForStatus) * 100;
    console.log(`🔍 DEBUG getTypePercentage - ${type}/${status}:`, { 
      typeValue: statusData[type], 
      totalForStatus, 
      percentage 
    });
    
    return percentage;
  }

  /**
   * ✨ NOVO: Verificar se há dados de tipo para um status específico
   */
  hasAnyTypeData(status: 'concluded' | 'active' | 'pending' | 'delayed'): boolean {
    const statusData = this.data[`${status}ByType` as keyof VolumeData] as any;
    if (!statusData) return false;
    
    return statusData.firstMile > 0 || statusData.lineHaul > 0 || statusData.lastMile > 0 || statusData.custom > 0;
  }
}
