import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouteStop } from '../route-stops.interface';

@Component({
  selector: 'app-route-stop-card',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="route-stop-card" 
         [class.selected]="isSelected"
         [class.dragging]="isDragging"
         [attr.data-stop-id]="stop.id"
         draggable="true"
         (dragstart)="onDragStart($event)"
         (dragend)="onDragEnd($event)"
         (click)="onCardClick()">
      
      <!-- 📍 Cabeçalho do Card -->
      <div class="card-header">
        <div class="sequence-badge">
          <i class="fas fa-map-marker-alt"></i>
          {{stop.sequence}}
        </div>
        
        <div class="stop-type">
          <i [class]="getTypeIcon()" [style.color]="getTypeColor()"></i>
          {{getTypeLabel()}}
        </div>
        
        <div class="status-badge" [class]="getStatusClass()">
          <i [class]="getStatusIcon()"></i>
          {{getStatusLabel()}}
        </div>
      </div>
      
      <!-- 📍 Informações Principais -->
      <div class="card-body">
        <div class="address-info">
          <h4 class="address-title">{{stop.location.address}}</h4>
          <p class="address-details">
            {{stop.location.city}}, {{stop.location.state}}
          </p>
        </div>
        
        <!-- ⏰ Data e Hora -->
        <div class="datetime-info" *ngIf="stop.scheduledTime">
          <i class="fas fa-clock text-primary"></i>
          <span>{{formatDateTime(stop.scheduledTime)}}</span>
        </div>
        
        <!-- 📦 Informações de Carga -->
        <div class="cargo-info" *ngIf="hasCargoInfo()">
          <div class="cargo-item" *ngIf="stop.packages">
            <i class="fas fa-box"></i>
            <span>{{stop.packages}} volumes</span>
          </div>
          <div class="cargo-item" *ngIf="stop.weight">
            <i class="fas fa-weight-hanging"></i>
            <span>{{stop.weight}}kg</span>
          </div>
        </div>
        
        <!-- 📄 Documento Fiscal -->
        <div class="fiscal-document" *ngIf="stop.fiscalDocument">
          <div class="document-badge" [class]="getFiscalDocumentClass()">
            <i class="fas fa-file-invoice"></i>
            <span>{{stop.fiscalDocument.documentType}}: {{stop.fiscalDocument.documentNumber}}</span>
            <i class="fas fa-check-circle" *ngIf="stop.fiscalDocument.status === 'validated'"></i>
            <i class="fas fa-exclamation-triangle" *ngIf="stop.fiscalDocument.status === 'error'"></i>
          </div>
        </div>
        
        <!-- 📝 Notas -->
        <div class="notes-info" *ngIf="stop.notes">
          <i class="fas fa-sticky-note text-warning"></i>
          <span class="notes-text">{{getTruncatedNotes()}}</span>
        </div>
      </div>
      
      <!-- 🎯 Ações do Card -->
      <div class="card-actions">
        <button 
          class="btn-action btn-edit"
          (click)="onEdit($event)"
          title="Editar parada">
          <i class="fas fa-edit"></i>
        </button>
        
        <button 
          class="btn-action btn-document"
          (click)="onViewDocument($event)"
          [disabled]="!stop.fiscalDocument"
          title="Ver documento fiscal">
          <i class="fas fa-file-invoice"></i>
        </button>
        
        <button 
          class="btn-action btn-location"
          (click)="onLocateOnMap($event)"
          title="Localizar no mapa">
          <i class="fas fa-map-marker-alt"></i>
        </button>
        
        <button 
          class="btn-action btn-delete"
          (click)="onDelete($event)"
          title="Excluir parada">
          <i class="fas fa-trash"></i>
        </button>
      </div>
      
      <!-- 🔄 Drag Handle -->
      <div class="drag-handle" title="Arrastar para reordenar">
        <i class="fas fa-grip-vertical"></i>
      </div>
    </div>
  `,
  styleUrl: './route-stop-card.component.scss'
})
export class RouteStopCardComponent {
  @Input() stop!: RouteStop;
  @Input() isSelected = false;
  @Input() isDragging = false;

  @Output() cardClick = new EventEmitter<RouteStop>();
  @Output() editClick = new EventEmitter<RouteStop>();
  @Output() deleteClick = new EventEmitter<RouteStop>();
  @Output() documentClick = new EventEmitter<RouteStop>();
  @Output() locateClick = new EventEmitter<RouteStop>();
  @Output() dragStart = new EventEmitter<{ stop: RouteStop; event: DragEvent }>();
  @Output() dragEnd = new EventEmitter<{ stop: RouteStop; event: DragEvent }>();

  // ========================================
  // 🎯 EVENTOS DE INTERAÇÃO
  // ========================================

  onCardClick(): void {
    this.cardClick.emit(this.stop);
  }

  onEdit(event: Event): void {
    event.stopPropagation();
    this.editClick.emit(this.stop);
  }

  onDelete(event: Event): void {
    event.stopPropagation();
    this.deleteClick.emit(this.stop);
  }

  onViewDocument(event: Event): void {
    event.stopPropagation();
    this.documentClick.emit(this.stop);
  }

  onLocateOnMap(event: Event): void {
    event.stopPropagation();
    this.locateClick.emit(this.stop);
  }

  onDragStart(event: DragEvent): void {
    this.dragStart.emit({ stop: this.stop, event });
  }

  onDragEnd(event: DragEvent): void {
    this.dragEnd.emit({ stop: this.stop, event });
  }

  // ========================================
  // 🎨 MÉTODOS DE APRESENTAÇÃO
  // ========================================

  getTypeIcon(): string {
    switch (this.stop.type) {
      case 'pickup': return 'fas fa-arrow-up';
      case 'delivery': return 'fas fa-arrow-down';
      case 'rest': return 'fas fa-coffee';
      case 'fuel': return 'fas fa-gas-pump';
      default: return 'fas fa-map-marker-alt';
    }
  }

  getTypeColor(): string {
    switch (this.stop.type) {
      case 'pickup': return '#28a745';
      case 'delivery': return '#dc3545';
      case 'rest': return '#6c757d';
      case 'fuel': return '#ffc107';
      default: return '#007bff';
    }
  }

  getTypeLabel(): string {
    switch (this.stop.type) {
      case 'pickup': return 'Coleta';
      case 'delivery': return 'Entrega';
      case 'rest': return 'Descanso';
      case 'fuel': return 'Combustível';
      default: return 'Parada';
    }
  }

  getStatusClass(): string {
    return `status-${this.stop.status}`;
  }

  getStatusIcon(): string {
    switch (this.stop.status) {
      case 'pending': return 'fas fa-clock';
      case 'completed': return 'fas fa-check-circle';
      case 'failed': return 'fas fa-times-circle';
      case 'skipped': return 'fas fa-forward';
      default: return 'fas fa-question-circle';
    }
  }

  getStatusLabel(): string {
    switch (this.stop.status) {
      case 'pending': return 'Pendente';
      case 'completed': return 'Concluída';
      case 'failed': return 'Falhou';
      case 'skipped': return 'Ignorada';
      default: return 'Desconhecido';
    }
  }

  getFiscalDocumentClass(): string {
    if (!this.stop.fiscalDocument) return '';
    
    switch (this.stop.fiscalDocument.status) {
      case 'validated': return 'document-validated';
      case 'error': return 'document-error';
      default: return 'document-pending';
    }
  }

  hasCargoInfo(): boolean {
    return !!(this.stop.packages || this.stop.weight);
  }

  formatDateTime(date: Date): string {
    return new Intl.DateTimeFormat('pt-BR', {
      day: '2-digit',
      month: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).format(new Date(date));
  }

  getTruncatedNotes(): string {
    if (!this.stop.notes) return '';
    return this.stop.notes.length > 50 
      ? this.stop.notes.substring(0, 50) + '...'
      : this.stop.notes;
  }
} 