import { Component, EventEmitter, Input, Output, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';

import { CsvImporterService } from './csv-importer.service';
import { 
  CsvFile, 
  CsvFileStatus, 
  CsvValidationResult, 
  ImportResult,
  CsvImporterConfig 
} from './csv-importer.interface';

/**
 * 📊 CsvImporterComponent
 * 
 * Componente de importação de CSV que funciona em dois contextos:
 * 1. 📋 SubTab - integrado ao sistema de abas
 * 2. 🪟 Modal - como diálogo independente
 * 
 * Segue fielmente o padrão do ImageUploaderComponent
 */
@Component({
  selector: 'app-csv-importer',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './csv-importer.component.html',
  styleUrls: ['./csv-importer.component.scss']
})
export class CsvImporterComponent implements OnInit, OnDestroy {

  // ========================================
  // 🎛️ INPUTS (configuração)
  // ========================================

  @Input() maxSizeMb: number = 10;
  @Input() allowMultiple: boolean = false; // account-payable sempre false
  @Input() showPreview: boolean = true;
  @Input() autoUpload: boolean = false;
  @Input() acceptMessage: string = 'Arraste um arquivo CSV aqui ou clique para selecionar';
  
  // Para uso em modais
  @Input() isModal: boolean = false;
  @Input() modalTitle: string = 'Importar Contas a Pagar';

  // ========================================
  // 📤 OUTPUTS (eventos)
  // ========================================

  @Output() fileSelected = new EventEmitter<CsvFile>();
  @Output() validationCompleted = new EventEmitter<CsvValidationResult>();
  @Output() uploadCompleted = new EventEmitter<string>(); // fileId
  @Output() importCompleted = new EventEmitter<ImportResult>();
  @Output() error = new EventEmitter<string>();
  @Output() statusChanged = new EventEmitter<{ file: CsvFile; status: CsvFileStatus }>();

  // Para modais
  @Output() modalClose = new EventEmitter<void>();

  // ========================================
  // 🎯 ESTADO DO COMPONENTE
  // ========================================

  selectedFile: CsvFile | null = null;
  isDragOver: boolean = false;
  isProcessing: boolean = false;
  
  private subscriptions: Subscription[] = [];

  // ========================================
  // 🎪 LIFECYCLE
  // ========================================

  constructor(
    private csvImporterService: CsvImporterService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    console.log('📊 CsvImporterComponent inicializado', {
      isModal: this.isModal,
      maxSizeMb: this.maxSizeMb,
      allowMultiple: this.allowMultiple
    });
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  // ========================================
  // 📁 SELEÇÃO DE ARQUIVO
  // ========================================

  onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (!input.files || input.files.length === 0) return;

    const file = input.files[0];
    this.processSelectedFile(file);
    
    // Limpar input para permitir seleção do mesmo arquivo
    input.value = '';
  }

  onDragOver(event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = true;
  }

  onDragLeave(event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = false;
  }

  onDrop(event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = false;

    const files = event.dataTransfer?.files;
    if (!files || files.length === 0) return;

    const file = files[0];
    

    
    this.processSelectedFile(file);
  }

  private processSelectedFile(file: File): void {
    console.log('📁 Arquivo selecionado:', file.name);
    
    // Validação local
    const validation = this.csvImporterService.validateFile(file, this.maxSizeMb);
    
    console.log('🔍 Resultado da validação local:', validation);
    
    if (!validation.valid) {
      console.log('❌ Arquivo inválido:', validation.errors);
      this.emitError(validation.errors.join(', '));
      return;
    }

    // Criar objeto CsvFile
    const csvFile: CsvFile = {
      id: this.generateFileId(),
      file,
      fileName: file.name,
      size: file.size,
      status: 'pending',
      createdAt: new Date()
    };

    this.selectedFile = csvFile;
    this.fileSelected.emit(csvFile);

    // Auto-validar se configurado
    if (this.autoUpload) {
      this.validateFile();
    }
  }

  private generateFileId(): string {
    return `csv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // ========================================
  // 🔍 VALIDAÇÃO
  // ========================================

  validateFile(): void {
    if (!this.selectedFile) return;

    this.updateFileStatus('validating');
    this.isProcessing = true;

    const subscription = this.csvImporterService.validateCsv(this.selectedFile.file)
      .subscribe({
        next: (result: CsvValidationResult) => {
          console.log('✅ Validação concluída:', result);
          
          if (this.selectedFile) {
            this.selectedFile.validationResult = result;
            
            if (result.valid) {
              this.updateFileStatus('validated');
              this.validationCompleted.emit(result);
            } else {
              this.updateFileStatus('error');
              this.emitError(`Validação falhou: ${result.errors?.join(', ')}`);
            }
          }
          
          this.isProcessing = false;
        },
        error: (error) => {
          console.error('❌ Erro na validação:', error);
          this.updateFileStatus('error');
          this.emitError(`Erro na validação: ${error.message}`);
          this.isProcessing = false;
        }
      });

    this.subscriptions.push(subscription);
  }

  // ========================================
  // ⬆️ UPLOAD
  // ========================================

  uploadFile(): void {
    if (!this.selectedFile || this.selectedFile.status !== 'validated') {
      this.emitError('Arquivo deve ser validado antes do upload');
      return;
    }

    this.updateFileStatus('uploading');
    this.isProcessing = true;

    const subscription = this.csvImporterService.uploadCsv(this.selectedFile.file)
      .subscribe({
        next: (fileId: string) => {
          console.log('⬆️ Upload concluído, fileId:', fileId);
          
          if (this.selectedFile) {
            this.selectedFile.uploadedFileId = fileId;
            this.updateFileStatus('uploaded');
            this.uploadCompleted.emit(fileId);
          }
          
          this.isProcessing = false;
        },
        error: (error) => {
          console.error('❌ Erro no upload:', error);
          this.updateFileStatus('error');
          this.emitError(`Erro no upload: ${error.message}`);
          this.isProcessing = false;
        }
      });

    this.subscriptions.push(subscription);
  }

  // ========================================
  // 📥 IMPORTAÇÃO
  // ========================================

  importFile(): void {
    if (!this.selectedFile || !this.selectedFile.uploadedFileId) {
      this.emitError('Arquivo deve ser enviado antes da importação');
      return;
    }

    this.updateFileStatus('importing');
    this.isProcessing = true;

    const subscription = this.csvImporterService.importCsv(this.selectedFile.uploadedFileId)
      .subscribe({
        next: (result: ImportResult) => {
          console.log('📥 Importação concluída:', result);
          
          if (result.success) {
            this.updateFileStatus('imported');
          } else {
            this.updateFileStatus('failed');
            this.emitError(`Importação falhou: ${result.message}`);
          }
          
          this.importCompleted.emit(result);
          this.isProcessing = false;
        },
        error: (error) => {
          console.error('❌ Erro na importação:', error);
          this.updateFileStatus('failed');
          this.emitError(`Erro na importação: ${error.message}`);
          this.isProcessing = false;
        }
      });

    this.subscriptions.push(subscription);
  }

  // ========================================
  // 🗑️ REMOÇÃO E LIMPEZA
  // ========================================

  removeFile(): void {
    if (this.isProcessing) return;

    this.selectedFile = null;
    this.isProcessing = false;
    console.log('🗑️ Arquivo removido');
  }

  clearAll(): void {
    this.removeFile();
  }

  // ========================================
  // 🔄 UTILITÁRIOS
  // ========================================

  private updateFileStatus(status: CsvFileStatus): void {
    if (this.selectedFile) {
      this.selectedFile.status = status;
      this.statusChanged.emit({ file: this.selectedFile, status });
      this.cdr.detectChanges();
    }
  }

  private emitError(message: string): void {
    console.error('🚨 CSV Importer Error:', message);
    this.error.emit(message);
  }

  // ========================================
  // 🎨 HELPERS PARA TEMPLATE
  // ========================================

  getStatusLabel(status: CsvFileStatus): string {
    const labels: Record<CsvFileStatus, string> = {
      pending: 'Aguardando validação',
      validating: 'Validando...',
      validated: 'Validado',
      error: 'Erro na validação',
      uploading: 'Enviando...',
      uploaded: 'Pronto para importar',
      importing: 'Importando...',
      imported: 'Importado com sucesso',
      failed: 'Falha na importação'
    };
    return labels[status] || status;
  }

  getStatusIcon(status: CsvFileStatus): string {
    const icons: Record<CsvFileStatus, string> = {
      pending: 'fa-clock',
      validating: 'fa-spinner fa-spin',
      validated: 'fa-check-circle',
      error: 'fa-exclamation-triangle',
      uploading: 'fa-arrow-up',
      uploaded: 'fa-check',
      importing: 'fa-download',
      imported: 'fa-check-circle',
      failed: 'fa-times-circle'
    };
    return icons[status] || 'fa-file';
  }

  getStatusClass(status: CsvFileStatus): string {
    return `status-${status}`;
  }

  formatFileSize(bytes: number): string {
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(1)} ${units[unitIndex]}`;
  }

  canValidate(): boolean {
    return this.selectedFile?.status === 'pending' && !this.isProcessing;
  }

  canUpload(): boolean {
    return this.selectedFile?.status === 'validated' && !this.isProcessing;
  }

  canImport(): boolean {
    return this.selectedFile?.status === 'uploaded' && !this.isProcessing;
  }

  canRemove(): boolean {
    return !this.isProcessing;
  }

  // ========================================
  // 🪟 MODAL ESPECÍFICO
  // ========================================

  closeModal(): void {
    this.modalClose.emit();
  }

  // ========================================
  // 🛡️ SAFE GETTERS PARA TEMPLATE
  // ========================================

  get validationResult() {
    return this.selectedFile?.validationResult;
  }

  get validationErrors() {
    return this.selectedFile?.validationResult?.errors || [];
  }

  get validationWarnings() {
    return this.selectedFile?.validationResult?.warnings || [];
  }

  get validationSummary() {
    return this.selectedFile?.validationResult?.summary;
  }

  get validationPreview() {
    return this.selectedFile?.validationResult?.preview;
  }
} 