/**
 * 📝 RouteStopFormComponent - Formulário Lateral Reativo
 * 
 * Componente responsável pelo formulário completo de criação/edição de paradas
 * com validações, autocomplete de endereço e integração com documentos fiscais.
 */

import { Component, Input, Output, EventEmitter, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subject, debounceTime, distinctUntilChanged, takeUntil } from 'rxjs';
import { RouteStop, FiscalDocument } from '../route-stops.interface';

@Component({
  selector: 'app-route-stop-form',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="route-stop-form" [class.visible]="isVisible">
      
      <!-- 📝 Cabeçalho do Formulário -->
      <div class="form-header">
        <h3>
          <i [class]="getFormIcon()"></i>
          {{getFormTitle()}}
        </h3>
        <button 
          class="btn-close"
          type="button"
          (click)="onCancel()"
          title="Fechar formulário">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <!-- 📋 Formulário Reativo -->
      <form [formGroup]="stopForm" (ngSubmit)="onSubmit()" class="form-content">
        
        <!-- 🎯 Tipo da Parada -->
        <div class="form-group">
          <label for="type" class="form-label required">
            <i class="fas fa-tag"></i>
            Tipo da Parada
          </label>
          <select 
            id="type"
            formControlName="type"
            class="form-control"
            [class.is-invalid]="isFieldInvalid('type')">
            <option value="">Selecione o tipo</option>
            <option value="pickup">📦 Coleta</option>
            <option value="delivery">🚚 Entrega</option>
            <option value="rest">☕ Descanso</option>
            <option value="fuel">⛽ Combustível</option>
          </select>
          <div class="invalid-feedback" *ngIf="isFieldInvalid('type')">
            Tipo da parada é obrigatório
          </div>
        </div>
        
        <!-- 📍 Endereço -->
        <div class="form-group">
          <label for="address" class="form-label required">
            <i class="fas fa-map-marker-alt"></i>
            Endereço
          </label>
          <div class="address-input-group">
            <input 
              id="address"
              type="text"
              formControlName="address"
              class="form-control"
              [class.is-invalid]="isFieldInvalid('address')"
              placeholder="Digite o endereço completo"
              (input)="onAddressInput($event)">
            <button 
              type="button"
              class="btn-search-address"
              (click)="searchAddress()"
              [disabled]="!stopForm.get('address')?.value"
              title="Buscar endereço">
              <i class="fas fa-search"></i>
            </button>
          </div>
          <div class="invalid-feedback" *ngIf="isFieldInvalid('address')">
            Endereço é obrigatório
          </div>
        </div>
        
        <!-- 🏙️ Cidade e Estado -->
        <div class="form-row">
          <div class="form-group col-8">
            <label for="city" class="form-label">
              <i class="fas fa-city"></i>
              Cidade
            </label>
            <input 
              id="city"
              type="text"
              formControlName="city"
              class="form-control"
              placeholder="Cidade">
          </div>
          <div class="form-group col-4">
            <label for="state" class="form-label">
              <i class="fas fa-map"></i>
              Estado
            </label>
            <input 
              id="state"
              type="text"
              formControlName="state"
              class="form-control"
              placeholder="UF"
              maxlength="2">
          </div>
        </div>
        
        <!-- ⏰ Data e Hora Programada -->
        <div class="form-group">
          <label for="scheduledTime" class="form-label">
            <i class="fas fa-clock"></i>
            Data e Hora Programada
          </label>
          <input 
            id="scheduledTime"
            type="datetime-local"
            formControlName="scheduledTime"
            class="form-control">
        </div>
        
        <!-- 📦 Informações de Carga -->
        <div class="form-section">
          <h4 class="section-title">
            <i class="fas fa-box"></i>
            Informações de Carga
          </h4>
          
          <div class="form-row">
            <div class="form-group col-6">
              <label for="packages" class="form-label">
                <i class="fas fa-boxes"></i>
                Volumes
              </label>
              <input 
                id="packages"
                type="number"
                formControlName="packages"
                class="form-control"
                placeholder="0"
                min="0">
            </div>
            <div class="form-group col-6">
              <label for="weight" class="form-label">
                <i class="fas fa-weight-hanging"></i>
                Peso (kg)
              </label>
              <input 
                id="weight"
                type="number"
                formControlName="weight"
                class="form-control"
                placeholder="0.0"
                min="0"
                step="0.1">
            </div>
          </div>
          
          <div class="form-group">
            <label for="referenceNumber" class="form-label">
              <i class="fas fa-hashtag"></i>
              Número de Referência
            </label>
            <input 
              id="referenceNumber"
              type="text"
              formControlName="referenceNumber"
              class="form-control"
              placeholder="Número de referência do cliente">
          </div>
        </div>
        
        <!-- 📝 Observações -->
        <div class="form-group">
          <label for="notes" class="form-label">
            <i class="fas fa-sticky-note"></i>
            Observações
          </label>
          <textarea 
            id="notes"
            formControlName="notes"
            class="form-control"
            rows="3"
            placeholder="Observações adicionais sobre a parada"></textarea>
        </div>
        
        <!-- 📄 Documento Fiscal -->
        <div class="form-section">
          <div class="section-header">
            <h4 class="section-title">
              <i class="fas fa-file-invoice"></i>
              Documento Fiscal
            </h4>
            <button 
              type="button"
              class="btn-add-document"
              (click)="onAddDocument()"
              [disabled]="!canAddDocument()">
              <i class="fas fa-plus"></i>
              Adicionar NFe/NFCe
            </button>
          </div>
          
          <!-- Preview do documento se existir -->
          <div class="document-preview" *ngIf="hasDocument()">
            <div class="document-info">
              <i class="fas fa-file-invoice text-success"></i>
              <span>{{getDocumentSummary()}}</span>
            </div>
            <button 
              type="button"
              class="btn-remove-document"
              (click)="onRemoveDocument()"
              title="Remover documento">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
        
        <!-- 🎯 Ações do Formulário -->
        <div class="form-actions">
          <button 
            type="submit"
            class="btn btn-primary"
            [disabled]="!stopForm.valid || isSubmitting">
            <i class="fas fa-save" *ngIf="!isSubmitting"></i>
            <i class="fas fa-spinner fa-spin" *ngIf="isSubmitting"></i>
            {{isSubmitting ? 'Salvando...' : getSaveButtonText()}}
          </button>
          
          <button 
            type="button"
            class="btn btn-secondary"
            (click)="onCancel()"
            [disabled]="isSubmitting">
            <i class="fas fa-times"></i>
            Cancelar
          </button>
        </div>
        
      </form>
      
    </div>
  `,
  styleUrl: './route-stop-form.component.scss'
})
export class RouteStopFormComponent implements OnInit, OnDestroy {
  @Input() mode: 'create' | 'edit' = 'create';
  @Input() routeStop: RouteStop | null = null;
  @Input() isVisible = false;
  
  @Output() formSubmit = new EventEmitter<Partial<RouteStop>>();
  @Output() formCancel = new EventEmitter<void>();
  @Output() addFiscalDocument = new EventEmitter<string>();
  
  stopForm!: FormGroup;
  isSubmitting = false;
  currentDocument: FiscalDocument | null = null;
  
  private destroy$ = new Subject<void>();
  
  constructor(
    private fb: FormBuilder,
    private cdr: ChangeDetectorRef
  ) {
    this.initializeForm();
  }
  
  ngOnInit(): void {
    this.setupFormWatchers();
    this.loadRouteStopData();
  }
  
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
  
  // ========================================
  // 🎯 INICIALIZAÇÃO DO FORMULÁRIO
  // ========================================
  
  private initializeForm(): void {
    this.stopForm = this.fb.group({
      type: ['', [Validators.required]],
      address: ['', [Validators.required]],
      city: [''],
      state: [''],
      scheduledTime: [''],
      packages: [0, [Validators.min(0)]],
      weight: [0, [Validators.min(0)]],
      referenceNumber: [''],
      notes: ['']
    });
  }
  
  private setupFormWatchers(): void {
    // Watch para mudanças no endereço (debounce para autocomplete)
    this.stopForm.get('address')?.valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe(address => {
        if (address && address.length > 10) {
          this.autoCompleteAddress(address);
        }
      });
  }
  
  private loadRouteStopData(): void {
    if (this.routeStop && this.mode === 'edit') {
      this.stopForm.patchValue({
        type: this.routeStop.type,
        address: this.routeStop.location.address,
        city: this.routeStop.location.city,
        state: this.routeStop.location.state,
        scheduledTime: this.formatDateTimeForInput(this.routeStop.scheduledTime),
        packages: this.routeStop.packages || 0,
        weight: this.routeStop.weight || 0,
        referenceNumber: this.routeStop.referenceNumber || '',
        notes: this.routeStop.notes || ''
      });
      
      this.currentDocument = this.routeStop.fiscalDocument || null;
      this.cdr.detectChanges();
    }
  }
  
  // ========================================
  // 🎯 EVENTOS DO FORMULÁRIO
  // ========================================
  
  onSubmit(): void {
    if (this.stopForm.valid && !this.isSubmitting) {
      this.isSubmitting = true;
      
      const formData = this.stopForm.value;
      const stopData: Partial<RouteStop> = {
        type: formData.type,
        location: {
          address: formData.address,
          city: formData.city || '',
          state: formData.state || '',
          coordinates: { lat: 0, lng: 0 } // TODO: Obter coordenadas do geocoding
        },
        scheduledTime: formData.scheduledTime ? new Date(formData.scheduledTime) : undefined,
        packages: formData.packages || undefined,
        weight: formData.weight || undefined,
        referenceNumber: formData.referenceNumber || undefined,
        notes: formData.notes || undefined,
        fiscalDocument: this.currentDocument || undefined
      };
      
      this.formSubmit.emit(stopData);
      
      // Reset submitting state after a delay
      setTimeout(() => {
        this.isSubmitting = false;
        this.cdr.detectChanges();
      }, 1000);
    }
  }
  
  onCancel(): void {
    this.stopForm.reset();
    this.currentDocument = null;
    this.formCancel.emit();
  }
  
  onAddDocument(): void {
    // Emitir evento para abrir modal de documento fiscal
    this.addFiscalDocument.emit('new-document');
  }
  
  onRemoveDocument(): void {
    this.currentDocument = null;
    this.cdr.detectChanges();
  }
  
  // ========================================
  // 🔍 AUTOCOMPLETE DE ENDEREÇO
  // ========================================
  
  onAddressInput(event: any): void {
    const address = event.target.value;
    // Input handler já é tratado pelo valueChanges
  }
  
  searchAddress(): void {
    const address = this.stopForm.get('address')?.value;
    if (address) {
      this.autoCompleteAddress(address);
    }
  }
  
  private autoCompleteAddress(address: string): void {
    // TODO: Implementar busca via ViaCEP ou Google Geocoding
    console.log('🔍 Buscando endereço:', address);
    
    // Simulação de resposta (remover quando implementar API real)
    if (address.toLowerCase().includes('são paulo')) {
      this.stopForm.patchValue({
        city: 'São Paulo',
        state: 'SP'
      }, { emitEvent: false });
    }
  }
  
  // ========================================
  // 🎨 MÉTODOS DE APRESENTAÇÃO
  // ========================================
  
  getFormIcon(): string {
    return this.mode === 'create' ? 'fas fa-plus' : 'fas fa-edit';
  }
  
  getFormTitle(): string {
    return this.mode === 'create' ? 'Nova Parada' : 'Editar Parada';
  }
  
  getSaveButtonText(): string {
    return this.mode === 'create' ? 'Criar Parada' : 'Atualizar Parada';
  }
  
  isFieldInvalid(fieldName: string): boolean {
    const field = this.stopForm.get(fieldName);
    return !!(field && field.invalid && (field.dirty || field.touched));
  }
  
  canAddDocument(): boolean {
    const type = this.stopForm.get('type')?.value;
    return type === 'pickup' || type === 'delivery';
  }
  
  hasDocument(): boolean {
    return !!this.currentDocument;
  }
  
  getDocumentSummary(): string {
    if (!this.currentDocument) return '';
    return `${this.currentDocument.documentType}: ${this.currentDocument.documentNumber}`;
  }
  
  // ========================================
  // 🔧 MÉTODOS AUXILIARES
  // ========================================
  
  private formatDateTimeForInput(date?: Date): string {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day}T${hours}:${minutes}`;
  }
} 