import { Component, Inject, OnInit, ChangeDetectorRef, output } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-preview-documents',
  standalone: false,
  templateUrl: './preview-documents.component.html',
  styleUrl: './preview-documents.component.css'
})
export class PreviewDocumentsComponent {
  


  public selectedSheet: string = '';
  public sheetNames: string[] = [];
  public isLoading: boolean = false;
  public fileName: string = '';
  public currentSheetData: any[][] = [];
  public editMode: boolean = false;
  public hasUnsavedChanges: boolean = false;
  public originalData: any = {};
  constructor(
    public dialogRef: MatDialogRef<PreviewDocumentsComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    if (this.data) {
      this.fileName = this.data.fileName;
      this.sheetNames = this.data.sheetNames;
      this.selectedSheet = this.sheetNames[0] || '';
      
      this.originalData = JSON.parse(JSON.stringify(this.data.sheets));
      
      console.log('Datos originales:', this.data.sheets[this.selectedSheet]);
      this.loadSheetData();
      
      console.log('Datos procesados:', this.currentSheetData);
    }
  }

  private loadSheetData(): void {
    if (this.data?.sheets && this.selectedSheet) {
      this.currentSheetData = this.data.sheets[this.selectedSheet] || [];
      
      this.processAndFormatData();
      this.normalizeTableData();
    }
  }


  private processAndFormatData(): void {
    this.currentSheetData = this.currentSheetData.map((row, rowIndex) => 
      row.map((cell, colIndex) => {
        if (rowIndex < 7) {
          return cell;
        }
        
        const isDateColumn = this.isDateColumn(colIndex);
        
        if (isDateColumn && typeof cell === 'number' && cell > 1000) {
          return this.excelDateToJSDate(cell);
        }
        
        return this.formatCellValue(cell);
      })
    );
  }




  private isDateColumn(colIndex: number): boolean {

    if (this.currentSheetData.length <= 7) {
      return false;
    }
    
    const headerRow = this.currentSheetData[6]; 
    if (!headerRow || !headerRow[colIndex]) {
      return false;
    }
    
    const header = String(headerRow[colIndex]).toLowerCase();
    const dateKeywords = [
      'fecha', 'date', 'garantía', 'garantia', 'adquisición', 'adquisicion', 
      'vencimiento', 'inicio', 'fin', 'vigencia', 'caducidad'
    ];
    
    return dateKeywords.some(keyword => header.includes(keyword));
  }

  private formatCellValue(value: any): any {
    if (value === null || value === undefined) {
      return '';
    }

    if (typeof value === 'number' && this.isExcelDate(value)) {
      return this.excelDateToJSDate(value);
    }

    if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
      const numValue = parseInt(value, 10);
      if (this.isExcelDate(numValue)) {
        return this.excelDateToJSDate(numValue);
      }
    }

    return value;
  }




  private isExcelDate(value: number): boolean {

    if (value < 1 || value > 80000) {
      return false;
    }
    
    if (value >= 40000 && value <= 60000) {
      return true;
    }
    
    if (Number.isInteger(value) && value > 25000 && value < 80000) {
      return true;
    }
    

    if (!Number.isInteger(value) && value > 25000 && value < 80000) {
      return true;
    }
    
    return false;
  }


  private excelDateToJSDate(excelDate: number): string {
    try {

      const excelEpoch = new Date(1899, 11, 30); 
      const jsDate = new Date(excelEpoch.getTime() + (excelDate * 24 * 60 * 60 * 1000));
      
     
      if (isNaN(jsDate.getTime())) {
        return excelDate.toString(); 
      }
      

      const day = jsDate.getDate().toString().padStart(2, '0');
      const month = (jsDate.getMonth() + 1).toString().padStart(2, '0');
      const year = jsDate.getFullYear();
      
      return `${year}/${month}/${day}`;
    } catch (error) {

      return excelDate.toString();
    }
  }

  private normalizeTableData(): void {
    if (this.currentSheetData.length === 0) return;
    
    const maxColumns = Math.max(...this.currentSheetData.map(row => row.length));
    
    this.currentSheetData = this.currentSheetData.map(row => {
      const normalizedRow = [...row];
      while (normalizedRow.length < maxColumns) {
        normalizedRow.push('');
      }
      return normalizedRow;
    });
    
    if (this.currentSheetData.length === 0) {
      this.currentSheetData = [new Array(26).fill('')]; 
    }
  }

  onSheetChange(sheetName: string): void {
    if (this.hasUnsavedChanges) {
      if (!confirm('Tienes cambios sin guardar. ¿Deseas continuar sin guardar?')) {
        return;
      }
    }
    
    this.selectedSheet = sheetName;
    this.loadSheetData();
    this.hasUnsavedChanges = false;
    this.cdr.detectChanges();
  }


  onCellChange(rowIndex: number, colIndex: number, event: any): void {
    const newValue = event.target.value;
    
    if (!this.currentSheetData[rowIndex]) {
      this.currentSheetData[rowIndex] = [];
    }
    
    this.currentSheetData[rowIndex][colIndex] = newValue;
    
 
    if (!this.data.sheets[this.selectedSheet]) {
      this.data.sheets[this.selectedSheet] = [];
    }
    

    if (!this.data.sheets[this.selectedSheet][rowIndex]) {
      this.data.sheets[this.selectedSheet][rowIndex] = [];
    }
    
    this.data.sheets[this.selectedSheet][rowIndex][colIndex] = newValue;
    
    this.hasUnsavedChanges = true;
  }


  onCellInput(rowIndex: number, colIndex: number, event: any): void {
    const newValue = event.target.value;
    

    if (!this.currentSheetData[rowIndex]) {
      this.currentSheetData[rowIndex] = [];
    }
    
    this.currentSheetData[rowIndex][colIndex] = newValue;
    this.hasUnsavedChanges = true;
  }


  onCellBlur(rowIndex: number, colIndex: number, event: any): void {
    const newValue = event.target.value;
    

    if (!this.data.sheets[this.selectedSheet]) {
      this.data.sheets[this.selectedSheet] = [];
    }
    
    if (!this.data.sheets[this.selectedSheet][rowIndex]) {
      this.data.sheets[this.selectedSheet][rowIndex] = [];
    }
    
    this.data.sheets[this.selectedSheet][rowIndex][colIndex] = newValue;
  }

  toggleEditMode(): void {
    this.editMode = !this.editMode;
    
    if (!this.editMode && this.hasUnsavedChanges) {
      console.log('Saliendo del modo edición. Datos modificados:', this.data.sheets[this.selectedSheet]);
    }
  }

  saveChanges(): void {
    console.log('Guardando cambios para la hoja:', this.selectedSheet);
    console.log('Datos modificados:', this.data.sheets[this.selectedSheet]);
    
    this.originalData = JSON.parse(JSON.stringify(this.data.sheets));
    this.hasUnsavedChanges = false;
    
    alert('Cambios guardados correctamente');
  }

  discardChanges(): void {
    if (confirm('¿Estás seguro de que deseas descartar todos los cambios?')) {
      this.data.sheets = JSON.parse(JSON.stringify(this.originalData));
      this.loadSheetData();
      this.hasUnsavedChanges = false;
      this.editMode = false;
    }
  }

  addRow(): void {
    const maxColumns = this.getMaxColumns();
    const newRow = new Array(maxColumns).fill('');
    this.currentSheetData.push(newRow);
    
    if (!this.data.sheets[this.selectedSheet]) {
      this.data.sheets[this.selectedSheet] = [];
    }
    this.data.sheets[this.selectedSheet].push(newRow);
    
    this.hasUnsavedChanges = true;
  }

  addColumn(): void {
    this.currentSheetData.forEach(row => {
      row.push('');
    });
    
    if (this.data.sheets[this.selectedSheet]) {
      this.data.sheets[this.selectedSheet].forEach((row: any[]) => {
        row.push('');
      });
    }
    
    this.hasUnsavedChanges = true;
  }

  deleteRow(rowIndex: number): void {
    if (confirm('¿Estás seguro de que deseas eliminar esta fila?')) {
      this.currentSheetData.splice(rowIndex, 1);
      
      if (this.data.sheets[this.selectedSheet]) {
        this.data.sheets[this.selectedSheet].splice(rowIndex, 1);
      }
      
      this.hasUnsavedChanges = true;
    }
  }

  deleteColumn(colIndex: number): void {
    if (confirm('¿Estás seguro de que deseas eliminar esta columna?')) {
      this.currentSheetData.forEach(row => {
        row.splice(colIndex, 1);
      });
      
      if (this.data.sheets[this.selectedSheet]) {
        this.data.sheets[this.selectedSheet].forEach((row: any[]) => {
          row.splice(colIndex, 1);
        });
      }
      
      this.hasUnsavedChanges = true;
    }
  }

  getTableHeaders(): string[] {
    const maxColumns = this.getMaxColumns();
    const headers: string[] = [];
    
    for (let i = 0; i < maxColumns; i++) {
      headers.push(this.getColumnName(i));
    }
    
    return headers;
  }

  private getMaxColumns(): number {
    if (this.currentSheetData.length === 0) return 26;
    return Math.max(...this.currentSheetData.map(row => row.length));
  }

  private getColumnName(colIndex: number): string {
    let result = '';
    while (colIndex >= 0) {
      result = String.fromCharCode(65 + (colIndex % 26)) + result;
      colIndex = Math.floor(colIndex / 26) - 1;
    }
    return result;
  }

  ValidateExcel(): void {
    console.log('Exportando Excel con datos:', this.data.sheets);
  }

  closeDialog(): void {
    if (this.hasUnsavedChanges) {
      if (!confirm('Tienes cambios sin guardar. ¿Deseas cerrar sin guardar?')) {
        return;
      }
    }
    
    this.dialogRef.close({
      hasChanges: this.hasUnsavedChanges,
      data: this.data.sheets
    });
  }

  getCellValue(row: any[], colIndex: number): string {
    const value = row[colIndex];
    return value !== null && value !== undefined ? String(value) : '';
  }

  getRowNumber(index: number): number {
    return index + 1;
  }

 
  trackByIndex(index: number, item: any): number {
    return index;
  }
}