import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ChangeDetectionStrategy } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { ColDef, GridApi, GridReadyEvent, SelectionChangedEvent } from 'ag-grid-community';
import { Observable, BehaviorSubject } from 'rxjs';

// Models
import { Field, CTA, Badge } from '../../../core/models';

/**
 * Vue liste modernisée avec AG-Grid skin premium
 */
@Component({
  selector: 'app-modern-list-view',
  templateUrl: './modern-list-view.component.html',
  styleUrls: ['./modern-list-view.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ModernListViewComponent implements OnInit {
  
  @ViewChild('agGrid', { static: true }) agGrid!: AgGridAngular;

  // Inputs
  @Input() title: string = '';
  @Input() description: string = '';
  @Input() icon: string = '';
  @Input() data: any[] = [];
  @Input() fields: Field[] = [];
  @Input() ctas: CTA[] = [];
  @Input() badges: Badge[] = [];
  @Input() loading = false;
  @Input() moduleName: string = '';
  @Input() domaineName: string = '';

  // Outputs
  @Output() actionTriggered = new EventEmitter<string>();
  @Output() rowSelected = new EventEmitter<any[]>();
  @Output() rowDoubleClicked = new EventEmitter<any>();
  @Output() filterChanged = new EventEmitter<any>();
  @Output() referenceClicked = new EventEmitter<{ module: string, id: string, uuid?: string, label: string }>();

  // État de la vue
  public selectedRows: any[] = [];
  public showFilters = false;
  public searchQuery = '';
  public viewMode: 'table' | 'cards' = 'table';

  // Configuration AG-Grid moderne
  public columnDefs: ColDef[] = [];
  public defaultColDef: ColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    floatingFilter: false,
    suppressMenu: true,
    minWidth: 120,
    flex: 1,
    cellClass: 'modern-cell',
    headerClass: 'modern-header-cell'
  };

  public gridOptions = {
    rowSelection: 'multiple',
    animateRows: false,
    enableCellChangeFlash: false,
    suppressCellFocus: true,
    suppressRowClickSelection: false,
    pagination: true,
    paginationPageSize: 50,
    suppressPaginationPanel: false,
    rowHeight: 48, // Réduit de 20%
    headerHeight: 40, // Réduit de 20%
    localeText: {
      page: 'Page',
      to: 'à',
      of: 'sur',
      next: 'Suivant',
      last: 'Dernier',
      first: 'Premier',
      previous: 'Précédent',
      loadingOoo: 'Chargement...',
      noRowsToShow: 'Aucune donnée à afficher'
    }
  };

  private gridApi!: GridApi;
  private referenceFields = new Map<string, Field>();

  ngOnInit(): void {
    this.buildColumns();
  }

  /**
   * Event handler pour l'initialisation de la grille
   */
  onGridReady(event: GridReadyEvent): void {
    this.gridApi = event.api;
    
    if (this.data && this.data.length > 0) {
      this.gridApi.setRowData(this.data);
      this.gridApi.sizeColumnsToFit();
    }
  }

  /**
   * Event handler pour le changement de sélection
   */
  onSelectionChanged(event: SelectionChangedEvent): void {
    this.selectedRows = this.gridApi.getSelectedRows();
    this.rowSelected.emit(this.selectedRows);
  }

  /**
   * Event handler pour le double-clic sur une ligne
   */
  onRowDoubleClicked(event: any): void {
    this.rowDoubleClicked.emit(event.data);
  }

  /**
   * Event handler pour le clic sur une cellule.
   * Détecte les clics sur les champs de type reference et émet referenceClicked.
   */
  onCellClicked(event: any): void {
    const fieldName = event.colDef?.field;
    const field = this.referenceFields.get(fieldName);
    if (!field) return;

    const value = event.value;
    if (!value || typeof value !== 'object') return;

    const id = value.id || value.uuid;
    if (!id) return;

    this.referenceClicked.emit({
      module: field.reference!,
      id: String(id),
      uuid: value.uuid,
      label: value.name || value.label || String(id)
    });
  }

  /**
   * Construit les colonnes AG-Grid depuis les métadonnées
   */
  private buildColumns(): void {
    // Stocker les champs de type reference pour la détection au clic
    this.referenceFields.clear();
    this.fields
      .filter(f => f.type === 'reference' && f.reference)
      .forEach(f => this.referenceFields.set(f.fieldname, f));

    this.columnDefs = [
      // Colonne de sélection
      {
        headerName: '',
        field: '',
        maxWidth: 60,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        checkboxSelection: true,
        filter: false,
        pinned: 'left',
        lockPinned: true,
        suppressMenu: true,
        suppressMovable: true,
        cellClass: 'selection-cell'
      },
      // Colonnes des données
      ...this.fields
        .filter(field => field.sequencelist !== undefined)
        .sort((a, b) => (a.sequencelist || 0) - (b.sequencelist || 0))
        .map(field => this.createColumnDef(field))
    ];
  }

  /**
   * Crée une définition de colonne moderne
   */
  private createColumnDef(field: Field): ColDef {
    const colDef: ColDef = {
      field: field.fieldname,
      headerName: field.displayName,
      width: field.minWidth || 150,
      filter: this.getFilterType(field.type),
      cellRenderer: this.getCellRenderer(field),
      valueFormatter: this.getValueFormatter(field),
      cellStyle: this.getCellStyle(field),
      headerClass: 'modern-header-cell',
      cellClass: 'modern-cell'
    };

    return colDef;
  }

  /**
   * Détermine le type de filtre
   */
  private getFilterType(fieldType: string): string {
    switch (fieldType) {
      case 'number':
      case 'integer':
      case 'double':
      case 'currency':
        return 'agNumberColumnFilter';
      case 'date':
      case 'datetime':
      case 'timestamp':
        return 'agDateColumnFilter';
      case 'boolean':
        return 'agSetColumnFilter';
      default:
        return 'agTextColumnFilter';
    }
  }

  /**
   * Renderer moderne pour les cellules
   */
  private getCellRenderer(field: Field): any {
    switch (field.type) {
      case 'picklist':
        return this.getModernPicklistRenderer(field);
      case 'reference':
        return this.getModernReferenceRenderer(field);
      case 'boolean':
        return this.getModernBooleanRenderer();
      default:
        return null;
    }
  }

  /**
   * Renderer moderne pour les picklists
   */
  private getModernPicklistRenderer(field: Field): any {
    return (params: any) => {
      const value = params.value;
      if (!value) return '';

      const option = field.options?.find(opt => opt.value === value);
      if (option) {
        const backgroundColor = option.color_back || '#F3F4F6';
        const textColor = option.color_font || '#374151';
        
        return `
          <span class="modern-badge" 
                style="background-color: ${backgroundColor}; 
                       color: ${textColor};">
            ${option.label || value}
          </span>
        `;
      }
      
      return `<span class="modern-badge">${value}</span>`;
    };
  }

  /**
   * Renderer moderne pour les références
   */
  private getModernReferenceRenderer(field: Field): any {
    return (params: any) => {
      const value = params.value;
      if (!value) return '';

      if (typeof value === 'object' && value.name) {
        const hasId = value.id || value.uuid;
        const icon = hasId ? 'open_in_new' : 'link';
        const clickableClass = hasId ? 'reference-clickable' : '';
        const title = hasId ? 'Cliquer pour ouvrir' : (field.reference || '');
        return `
          <span class="modern-reference ${clickableClass}" title="${title}">
            <i class="material-icons">${icon}</i>
            ${value.name}
          </span>
        `;
      }

      return `<span class="modern-reference">${value}</span>`;
    };
  }

  /**
   * Renderer moderne pour les booléens
   */
  private getModernBooleanRenderer(): any {
    return (params: any) => {
      const value = params.value;
      if (value === null || value === undefined) return '';
      
      const icon = value ? 'check_circle' : 'cancel';
      const color = value ? '#10B981' : '#EF4444';
      
      return `
        <span class="modern-boolean" style="color: ${color};">
          <i class="material-icons">${icon}</i>
        </span>
      `;
    };
  }

  /**
   * Formateur de valeur moderne
   */
  private getValueFormatter(field: Field): any {
    switch (field.type) {
      case 'currency':
        return (params: any) => {
          if (params.value != null) {
            return new Intl.NumberFormat('fr-FR', {
              style: 'currency',
              currency: 'EUR',
              minimumFractionDigits: 2
            }).format(params.value);
          }
          return '';
        };
      case 'date':
        return (params: any) => {
          if (params.value) {
            return new Date(params.value).toLocaleDateString('fr-FR');
          }
          return '';
        };
      case 'datetime':
        return (params: any) => {
          if (params.value) {
            return new Date(params.value).toLocaleString('fr-FR');
          }
          return '';
        };
      default:
        return null;
    }
  }

  /**
   * Style moderne des cellules
   */
  private getCellStyle(field: Field): any {
    const baseStyle = {
      display: 'flex',
      alignItems: 'center',
      padding: '8px 12px',
      fontSize: '13px',
      lineHeight: '1.4'
    };

    switch (field.type) {
      case 'currency':
      case 'number':
      case 'integer':
      case 'double':
        return {
          ...baseStyle,
          justifyContent: 'flex-end',
          fontWeight: '500',
          fontFamily: 'monospace'
        };
      case 'picklist':
        return {
          ...baseStyle,
          justifyContent: 'center'
        };
      default:
        return baseStyle;
    }
  }

  /**
   * Actions de la vue
   */
  onActionClick(action: string): void {
    this.actionTriggered.emit(action);
  }

  toggleFilters(): void {
    this.showFilters = !this.showFilters;
    this.defaultColDef.floatingFilter = this.showFilters;
    
    if (this.gridApi) {
      this.gridApi.setColumnDefs(this.columnDefs);
    }
  }

  toggleViewMode(): void {
    this.viewMode = this.viewMode === 'table' ? 'cards' : 'table';
  }

  onSearchChange(query: string): void {
    this.searchQuery = query;
    if (this.gridApi) {
      this.gridApi.setQuickFilter(query);
    }
  }

  clearSelection(): void {
    if (this.gridApi) {
      this.gridApi.deselectAll();
    }
  }

  selectAll(): void {
    if (this.gridApi) {
      this.gridApi.selectAll();
    }
  }

  exportData(): void {
    if (this.gridApi) {
      this.gridApi.exportDataAsCsv({
        fileName: `${this.moduleName}-${new Date().toISOString().split('T')[0]}.csv`
      });
    }
  }

  refreshData(): void {
    this.actionTriggered.emit('refresh');
  }

  /**
   * Helpers pour le template
   */
  getActiveModuleColor(): string {
    // Retourner la couleur du module actif
    return '#4AA8DC'; // Par défaut
  }

  getActiveModuleIcon(): string {
    return 'people'; // Par défaut
  }

  getActiveModuleName(): string {
    return this.title || 'Module';
  }

  getActiveModuleDescription(): string {
    return this.description || 'Description du module';
  }

  getTotalVisibleItems(): number {
    return this.data?.length || 0;
  }

  getLastUpdateTime(): string {
    return 'maintenant';
  }

  toggleSidebar(): void {
    // Émis vers le parent pour gérer l'état global
  }

  /**
   * Méthodes pour les KPI badges
   */
  getKpiColor(index: number): string {
    const colors = ['#4A90E2', '#7ED321', '#F5A623', '#D0021B', '#9013FE'];
    return colors[index % colors.length];
  }

  getDefaultKpiIcon(index: number): string {
    const icons = ['analytics', 'trending_up', 'bar_chart', 'pie_chart', 'show_chart'];
    return icons[index % icons.length];
  }

  /**
   * Méthodes pour les boutons d'action
   */
  getActionButtonClass(action: string): string {
    const classes: { [key: string]: string } = {
      'create': 'action-btn primary',
      'edit': 'action-btn secondary', 
      'delete': 'action-btn danger',
      'export': 'action-btn info',
      'refresh': 'action-btn light'
    };
    return classes[action] || 'action-btn';
  }

  getDefaultActionIcon(action: string): string {
    const icons: { [key: string]: string } = {
      'create': 'add',
      'edit': 'edit',
      'delete': 'delete',
      'export': 'download',
      'refresh': 'refresh',
      'filter': 'filter_list'
    };
    return icons[action] || 'more_vert';
  }

  /**
   * Gestion des permissions
   */
  hasCreatePermission(): boolean {
    // Pour l'instant, retourner true. À adapter selon les permissions réelles
    return true;
  }
}