/**
 * 📋 RouteStopsListComponent - Lista Lateral de Paradas
 * 
 * Componente responsável por exibir a lista de paradas com funcionalidades
 * de drag & drop, seleção e ações rápidas.
 */

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

@Component({
  selector: 'app-route-stops-list',
  standalone: true,
  imports: [CommonModule, RouteStopCardComponent],
  template: `
    <div class="route-stops-list" 
         (dragover)="onDragOver($event)"
         (drop)="onDrop($event)">
      
      <!-- 📋 Cabeçalho da Lista -->
      <div class="list-header">
        <div class="header-info">
          <h3>
            <i class="fas fa-list"></i>
            Paradas da Rota
          </h3>
          <span class="stops-count" *ngIf="stops.length > 0">
            {{stops.length}} parada{{stops.length > 1 ? 's' : ''}}
          </span>
        </div>
      </div>
      
      <!-- 🔄 Loading State -->
      <div class="loading-state" *ngIf="isLoading">
        <i class="fas fa-spinner fa-spin"></i>
        <span>Carregando paradas...</span>
      </div>
      
      <!-- 📋 Lista de Cards -->
      <div class="stops-container" *ngIf="!isLoading">
        
        <!-- 📍 Empty State -->
        <div class="empty-state" *ngIf="stops.length === 0">
          <i class="fas fa-map-marker-alt fa-2x text-muted"></i>
          <h4>Nenhuma parada cadastrada</h4>
          <p class="text-muted">
            Clique em "Nova Parada" para começar a planejar sua rota.
          </p>
        </div>
        
        <!-- 📍 Route Stop Cards -->
        <app-route-stop-card
          *ngFor="let stop of stops; trackBy: trackByStopId"
          [stop]="stop"
          [isSelected]="isStopSelected(stop)"
          [isDragging]="draggedStop?.id === stop.id"
          (cardClick)="onStopClick(stop)"
          (editClick)="onStopEdit(stop)"
          (deleteClick)="onStopDelete(stop)"
          (documentClick)="onStopDocument(stop)"
          (locateClick)="onStopLocate(stop)"
          (dragStart)="onStopDragStart($event)"
          (dragEnd)="onStopDragEnd($event)">
        </app-route-stop-card>
        
      </div>
      
      <!-- 📊 Lista Summary -->
      <div class="list-summary" *ngIf="stops.length > 0 && !isLoading">
        <div class="summary-stats">
          <div class="stat-item">
            <i class="fas fa-map-marker-alt text-primary"></i>
            <span>{{stops.length}} paradas</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-clock text-warning"></i>
            <span>{{getPendingStopsCount()}} pendentes</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-check-circle text-success"></i>
            <span>{{getCompletedStopsCount()}} concluídas</span>
          </div>
        </div>
      </div>
      
    </div>
  `,
  styleUrl: './route-stops-list.component.scss'
})
export class RouteStopsListComponent {
  @Input() stops: RouteStop[] = [];
  @Input() selectedStop: RouteStop | null = null;
  @Input() isLoading = false;
  
  @Output() stopSelected = new EventEmitter<RouteStop>();
  @Output() stopEdit = new EventEmitter<RouteStop>();
  @Output() stopDelete = new EventEmitter<RouteStop>();
  @Output() stopsReorder = new EventEmitter<RouteStop[]>();
  
  // Drag & Drop state
  draggedStop: RouteStop | null = null;
  
  // ========================================
  // 🎯 EVENTOS DOS CARDS
  // ========================================
  
  onStopClick(stop: RouteStop): void {
    this.stopSelected.emit(stop);
  }
  
  onStopEdit(stop: RouteStop): void {
    this.stopEdit.emit(stop);
  }
  
  onStopDelete(stop: RouteStop): void {
    this.stopDelete.emit(stop);
  }
  
  onStopDocument(stop: RouteStop): void {
    // TODO: Implementar visualização de documento
    console.log('📄 Ver documento da parada:', stop);
  }
  
  onStopLocate(stop: RouteStop): void {
    // TODO: Centralizar mapa na parada
    console.log('📍 Localizar parada no mapa:', stop);
  }
  
  // ========================================
  // 🔄 DRAG & DROP FUNCIONAL
  // ========================================
  
  onStopDragStart(event: { stop: RouteStop; event: DragEvent }): void {
    this.draggedStop = event.stop;
    if (event.event.dataTransfer) {
      event.event.dataTransfer.effectAllowed = 'move';
      event.event.dataTransfer.setData('text/plain', event.stop.id);
    }
    
    // Adicionar classe visual ao container
    this.addDragClass();
  }
  
  onStopDragEnd(event: { stop: RouteStop; event: DragEvent }): void {
    this.draggedStop = null;
    this.removeDragClass();
  }
  
  onDragOver(event: DragEvent): void {
    event.preventDefault();
    event.dataTransfer!.dropEffect = 'move';
    
    // Destacar área de drop
    const dropTarget = this.findDropTarget(event.target as Element);
    if (dropTarget && this.draggedStop) {
      this.highlightDropTarget(dropTarget);
    }
  }
  
  onDrop(event: DragEvent): void {
    event.preventDefault();
    
    if (!this.draggedStop) return;
    
    const dropTarget = this.findDropTarget(event.target as Element);
    if (!dropTarget) return;
    
    const targetStopId = dropTarget.getAttribute('data-stop-id');
    const targetStop = this.stops.find(stop => stop.id === targetStopId);
    
    if (!targetStop || targetStop.id === this.draggedStop.id) return;
    
    // Reordenar paradas
    const reorderedStops = this.reorderStops(this.draggedStop, targetStop);
    this.stopsReorder.emit(reorderedStops);
    
    this.draggedStop = null;
    this.removeDragClass();
    this.removeDropHighlight();
  }
  
  // ========================================
  // 🎨 MÉTODOS DE DRAG & DROP
  // ========================================
  
  private findDropTarget(element: Element | null): Element | null {
    while (element && !element.hasAttribute('data-stop-id')) {
      element = element.parentElement;
    }
    return element;
  }
  
  private reorderStops(draggedStop: RouteStop, targetStop: RouteStop): RouteStop[] {
    const newStops = [...this.stops];
    const draggedIndex = newStops.findIndex(stop => stop.id === draggedStop.id);
    const targetIndex = newStops.findIndex(stop => stop.id === targetStop.id);
    
    // Remove o item arrastado
    newStops.splice(draggedIndex, 1);
    
    // Insere na nova posição
    newStops.splice(targetIndex, 0, draggedStop);
    
    // Atualiza as sequências
    return newStops.map((stop, index) => ({
      ...stop,
      sequence: index + 1
    }));
  }
  
  private addDragClass(): void {
    const container = document.querySelector('.route-stops-list');
    container?.classList.add('dragging-active');
  }
  
  private removeDragClass(): void {
    const container = document.querySelector('.route-stops-list');
    container?.classList.remove('dragging-active');
  }
  
  private highlightDropTarget(target: Element): void {
    this.removeDropHighlight();
    target.classList.add('drop-target-highlight');
  }
  
  private removeDropHighlight(): void {
    const highlighted = document.querySelectorAll('.drop-target-highlight');
    highlighted.forEach(el => el.classList.remove('drop-target-highlight'));
  }
  
  // ========================================
  // 🎨 MÉTODOS AUXILIARES
  // ========================================
  
  trackByStopId(index: number, stop: RouteStop): string {
    return stop.id;
  }
  
  isStopSelected(stop: RouteStop): boolean {
    return this.selectedStop?.id === stop.id;
  }
  
  getPendingStopsCount(): number {
    return this.stops.filter(stop => stop.status === 'pending').length;
  }
  
  getCompletedStopsCount(): number {
    return this.stops.filter(stop => stop.status === 'completed').length;
  }
} 