import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';

import { CsvImporterComponent } from './csv-importer.component';
import { 
  CsvImporterModalData, 
  CsvFile, 
  CsvValidationResult, 
  ImportResult 
} from './csv-importer.interface';

/**
 * 🪟 CsvImporterModalComponent
 * 
 * Wrapper modal para o CsvImporterComponent usando MatDialog
 * Compatível com o sistema de modais existente do projeto
 */
@Component({
  selector: 'app-csv-importer-modal',
  standalone: true,
  imports: [
    CommonModule,
    MatDialogModule,
    CsvImporterComponent
  ],
  template: `
    <div class="csv-modal-overlay">
      <div class="csv-modal-container">
        
        <!-- 📊 CSV Importer integrado -->
        <app-csv-importer
          [isModal]="true"
          [modalTitle]="data.title || 'Importar CSV'"
          [maxSizeMb]="data.config.maxSizeMb"
          [allowMultiple]="data.config.allowMultiple"
          [showPreview]="data.config.showPreview"
          [autoUpload]="data.config.autoUpload"
          [acceptMessage]="data.config.acceptMessage || 'Selecione um arquivo CSV para importar'"
          (fileSelected)="onFileSelected($event)"
          (validationCompleted)="onValidationCompleted($event)"
          (uploadCompleted)="onUploadCompleted($event)"
          (importCompleted)="onImportCompleted($event)"
          (error)="onError($event)"
          (modalClose)="closeModal()">
        </app-csv-importer>
        
      </div>
    </div>
  `,
  styles: [`
    :host {
      --modal-bg-light: #f8f9fa;
      --modal-bg-dark: #2d3748;
      --modal-container-light: white;
      --modal-container-dark: #4a5568;
    }

    :host-context(.dark-theme) {
      --modal-bg-light: var(--modal-bg-dark);
      --modal-container-light: var(--modal-container-dark);
    }

    .csv-modal-overlay {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      background: var(--modal-bg-light);
      padding: 1rem;
    }

    .csv-modal-container {
      background: var(--modal-container-light);
      border-radius: 12px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
      width: 600px;
      max-width: 90vw;
      max-height: 90vh;
      overflow: hidden;
      animation: modalShow 0.3s ease-out;
    }

    :host-context(.dark-theme) .csv-modal-container {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
    }

    @keyframes modalShow {
      from {
        opacity: 0;
        transform: scale(0.95) translateY(-20px);
      }
      to {
        opacity: 1;
        transform: scale(1) translateY(0);
      }
    }

    // Responsive
    @media (max-width: 768px) {
      .csv-modal-container {
        width: 100%;
        height: 100%;
        border-radius: 0;
        max-width: none;
        max-height: none;
      }
    }
  `]
})
export class CsvImporterModalComponent {

  constructor(
    public dialogRef: MatDialogRef<CsvImporterModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: CsvImporterModalData
  ) {
    console.log('🪟 CSV Importer Modal inicializado:', data);
  }

  // ========================================
  // 📤 EVENT HANDLERS (proxy para parent)
  // ========================================

  onFileSelected(file: CsvFile): void {
    console.log('📁 Arquivo selecionado no modal:', file.fileName);
    // Opcional: emitir eventos para componente pai se necessário
  }

  onValidationCompleted(result: CsvValidationResult): void {
    console.log('✅ Validação concluída no modal:', result.valid);
    // Opcional: ações específicas do modal
  }

  onUploadCompleted(fileId: string): void {
    console.log('⬆️ Upload concluído no modal:', fileId);
    // Opcional: ações específicas do modal
  }

  onImportCompleted(result: ImportResult): void {
    console.log('📥 Importação concluída no modal:', result.success);
    
    if (result.success) {
      // Fechar modal com resultado de sucesso
      this.dialogRef.close({
        success: true,
        result: result,
        action: 'imported'
      });
    } else {
      // Manter modal aberto em caso de erro (usuário pode tentar novamente)
      console.warn('❌ Importação falhou:', result.message);
    }
  }

  onError(error: string): void {
    console.error('🚨 Erro no CSV Importer Modal:', error);
    // Opcional: mostrar snackbar ou toast
  }

  closeModal(): void {
    console.log('🔒 Fechando CSV Importer Modal');
    this.dialogRef.close({
      success: false,
      action: 'cancelled'
    });
  }
} 