import { Component, ChangeDetectorRef } from "@angular/core";
import { CommonModule, DatePipe } from "@angular/common";

import { TitleService } from "../../shared/services/theme/title.service";
import { HeaderActionsService } from "../../shared/services/header-actions.service";
import { FuelcontrollService } from "./fuelcontroll.service";
import { Fuelcontroll } from "./fuelcontroll.interface";
import { SnackNotifyService } from "../../shared/components/snack-notify/snack-notify.service";

import { TabSystemComponent } from "../../shared/components/tab-system/tab-system.component";
import { BaseDomainComponent, DomainConfig } from "../../shared/components/base-domain/base-domain.component";
import { TabFormConfig } from "../../shared/interfaces/generic-tab-form.interface";
import { TabFormConfigService } from "../../shared/components/tab-system/services/tab-form-config.service";

// Services para remote-select
import { VehiclesService } from "../vehicles/vehicles.service";
import { DriversService } from "../drivers/drivers.service";
import { SupplierService } from "../supplier/supplier.service";
import { CompanyService } from "../company/company.service";
import { DateRangeShortcuts } from "../../shared/utils/date-range.utils";

/**
 * 🎯 FuelcontrollComponent - Gestão de Controle de Combustível
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-fuelcontroll',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './fuelcontroll.component.html',
  styleUrl: './fuelcontroll.component.scss'
})
export class FuelcontrollComponent extends BaseDomainComponent<Fuelcontroll> {

  constructor(
    private fuelcontrollService: FuelcontrollService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService,
    private vehiclesService: VehiclesService,
    private driversService: DriversService,
    private supplierService: SupplierService,
    private companyService: CompanyService,
    private snackNotifyService: SnackNotifyService
  ) {
    super(titleService, headerActionsService, cdr, fuelcontrollService);
    this.registerFormConfig();
  }

  private registerFormConfig(): void {
    this.tabFormConfigService.registerFormConfig('fuelcontroll', () => this.getFormConfig());
  }

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'fuelcontroll',
      title: 'Controle de Combustível',      
      entityName: 'Abastecimento',
      pageSize: 500,
      subTabs: ['dados', 'localizacao', 'adicional'],
      filterConfig: {
        defaultFilters: [
          {
            field: 'status',
            operator: 'in', 
            value: ['SUPPLY_APPROVED', 'SUPPLY_REJECTED']
          },
          {
            field: 'startDate',
            operator: 'gte',
            value:  DateRangeShortcuts.today().date_start
          },
          {
            field: 'endDate',
            operator: 'lte',
            value:  DateRangeShortcuts.today().date_end
          }
        ],
        fieldsSearchDefault: ['licensePlates'],
        dateRangeFilter: true,
        dateFieldNames: {
          startField: 'startDate',
          endField: 'endDate'
        },
        companyFilter: true,
        searchConfig: {
          minSearchLength: 4,           // ✨ Só pesquisar após 3 caracteres
          debounceTime: 400,           // ✨ Aguardar 500ms após parar de digitar
          preserveSearchOnDataChange: true  // ✨ Não apagar o campo quando dados chegam
        }
      },
      bulkActions: [
        {
          id: 'export-data',
          label: 'Exportar Dados',
          icon: 'fas fa-download',
          requiresSelection: false,
          action: (selectedItems) => this.openExportDataLista()
        }
      ],
      columns: [
        { 
          field: "id", 
          header: "ID", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number" 
        },
        { field: "personName",
          header: "Motorista",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "text"
        },
        {
          field: "licensePlate",
          header: "Placa",
          searchField: "license_plates",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "text"
        },
        {
          field: "vehicleModel",
          header: "Modelo",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "text"
        },
        { 
          field: "companyName",
          header: "Empresa",
          filterField: "companyIds",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "text"
        },        
        { 
          field: "gasStationBrand",
          header: "Posto",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "text"
        },
        { 
          field: "odometer", 
          header: "Odômetro (Km)", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number" 
        },       
        {
          field: "status",
          header: "Status",
          sortable: true,
          filterable: true,
          allowHtml: true,
          search: false,
          searchType: "select",
          searchOptions: [
            { value: 'SUPPLY_APPROVED', label: 'Aprovado' },
            { value: 'SUPPLY_REJECTED', label: 'Negado' },
          ],
          label: (value: any) => {
            const statusConfig: { [key: string]: { label: string, class: string } } = {
              'SUPPLY_APPROVED': { label: 'Aprovado', class: 'status-approved' },
              'SUPPLY_REJECTED': { label: 'Negado', class: 'status-rejected' },
            };
            const config = statusConfig[value] || { label: value, class: 'status-unknown' };
            return `<span class="status-badge ${config.class}">${config.label}</span>`;
          }
        }, 
        { 
          field: "value", 
          header: "Valor", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number",          
          label: (value: any) => {
            if (!value) return '-';
            return `R$ ${Number(value).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;
          },
          footer: {
            type: 'sum',
            format: 'currency',
            label: 'Total:',
            precision: 2
          }
        },
        {
          field: "date",
          header: "Data Abastecimento",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy") || "-"
        },

      ]
    };
  }

  getFormConfig(): TabFormConfig {
    return {
      title: 'Dados do Controle de Combustível',
      titleFallback: 'Novo Abastecimento', 
      entityType: 'fuelcontroll',
      fields: [],      
      submitLabel: 'Salvar Abastecimento',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-info-circle',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['vehicleId', 'personId', 'supplierId', 'companyId', 'value'],
          fields: [
            {
              key: 'vehicleId',
              label: 'Veículo',
              type: 'remote-select',
              required: true,
              hideLabel: true,
              disabled: true,
              labelField: 'licensePlate',
              remoteConfig: {
                service: this.vehiclesService,
                valueField: 'id',
                displayField: 'license_plate',
                searchField: 'license_plate',
                modalTitle: 'Selecionar Veículo',
                placeholder: 'Selecione o veículo',
              }
            },
            {
              key: 'personId',
              label: 'Motorista',
              type: 'remote-select',
              required: true,
              hideLabel: true,
              disabled: true,
              labelField: 'personName',
              remoteConfig: {
                service: this.driversService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                modalTitle: 'Selecionar Motorista',
                placeholder: 'Selecione o motorista'
              }
            },
            {
              key: 'supplierId',
              label: 'Fornecedor',
              type: 'remote-select',
              required: true,
              hideLabel: true,
              labelField: 'supplierName',
              disabled: true,
              remoteConfig: {
                service: this.supplierService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                modalTitle: 'Selecionar Posto',
                placeholder: 'Selecione o Posto',
              }
            },
            {
              key: 'companyId',
              label: 'Empresa',
              type: 'remote-select',
              required: true,
              labelField: 'companyName',
              hideLabel: true,
              disabled: true,
              remoteConfig: {
                service: this.companyService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                modalTitle: 'Selecionar Empresa',
                placeholder: 'Selecione a empresa',
              }
            },
            {
              key: 'code',
              label: 'Código',
              type: 'text',
              required: false,
              disabled: true,
              placeholder: 'Código do controle'
            },
            {
              key: 'status',
              label: 'Status',
              type: 'select',
              required: false,
              disabled: true,
              options: [  
                { value: 'SUPPLY_APPROVED', label: 'Aprovado' },
                { value: 'SUPPLY_REJECTED', label: 'Negado' },
              ],
              placeholder: 'Status do controle'
            },
            {
              key: 'date',
              label: 'Data do Abastecimento',
              type: 'date',
              required: false,
              disabled: true,
              placeholder: 'Data do abastecimento'
            },
            {
              key: 'gasStationBrand',
              label: 'Bandeira do Posto',
              type: 'text',
              required: false,
              disabled: true,
              placeholder: 'Bandeira do posto de combustível'
            },          
            {
              key: 'value',
              label: 'Valor Total (R$)',
              type: 'number',
              required: true,
              disabled: true,
              placeholder: 'Valor total do abastecimento'
            },
            {
              key: 'odometer',
              label: 'Odômetro (Km)',
              type: 'number',
              required: false,
              disabled: true,
              placeholder: 'Quilometragem do veículo'
            }
          ]
        },
        {
          id: 'localizacao',
          label: 'Localização',
          icon: 'fa-map-marker-alt',
          enabled: true,
          order: 2,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            {
              key: 'lat',
              label: 'Latitude',
              type: 'number',
              required: false,
              placeholder: 'Latitude da localização'
            },
            {
              key: 'lon',
              label: 'Longitude',
              type: 'number',
              required: false,
              placeholder: 'Longitude da localização'
            },
            {
              key: 'imei',
              label: 'IMEI',
              type: 'text',
              required: false,
              placeholder: 'IMEI do dispositivo'
            },
            {
              key: 'battery',
              label: 'Bateria (%)',
              type: 'number',
              required: false,
              placeholder: 'Nível da bateria'
            }
          ]
        },
        {
          id: 'adicional',
          label: 'Informações Adicionais',
          icon: 'fa-info',
          enabled: true,
          order: 5,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            {
              key: 'keyTaxDocument',
              label: 'Chave Documento Fiscal',
              type: 'text',
              required: false,
              placeholder: 'Chave do documento fiscal'
            },
            {
              key: 'qrcodeData',
              label: 'Dados QR Code',
              type: 'text',
              required: false,
              placeholder: 'Dados do QR Code'
            },

          ]
        }
      ]
    };
  }

  protected override getNewEntityData(): Partial<Fuelcontroll> {
    return {
      vehicleId: 0,
      personId: 0,
      supplierId: 0,
      companyId: 0,
      code: '',
      keyTaxDocument: '',
      status: 'ATIVO',
      lat: 0,
      lon: 0,
      imei: '',
      battery: 0,
      gasStationBrand: '',    
      value: 0,
      odometer: 0,
      qrcodeData: '',
      date: '',
      items: []
    };
  }

  // ========================================
  // 📊 EXPORTAÇÃO DE DADOS
  // ========================================

  private openExportDataLista(): void {
    // Mostrar opções de período para o usuário
    this.showPeriodSelectionModal();
  }

  /**
   * 📅 Mostrar modal de seleção de período
   */
  private showPeriodSelectionModal(): void {
    const periodOptions = [
      { label: 'Hoje', value: 'today', description: 'Dados de hoje' },
      { label: 'Ontem', value: 'yesterday', description: 'Dados de ontem' },
      { label: 'Últimos 7 dias', value: 'last7Days', description: 'Última semana' },
      { label: 'Últimos 30 dias', value: 'last30Days', description: 'Último mês' },
      { label: 'Mês atual', value: 'currentMonth', description: 'Do início do mês até hoje' },
      { label: 'Mês anterior', value: 'previousMonth', description: 'Mês anterior' },
      { label: 'Ano atual', value: 'currentYear', description: 'Do início do ano até hoje' }
    ];

    // Criar elementos do modal
    const modalHtml = `
      <div class="period-selection-modal">
        <h3>Selecione o período para exportação</h3>
        <div class="period-options">
          ${periodOptions.map(option => `
            <div class="period-option" data-value="${option.value}">
              <div class="option-label">${option.label}</div>
              <div class="option-description">${option.description}</div>
            </div>
          `).join('')}
        </div>
        <div class="modal-actions">
          <button class="btn-cancel">Cancelar</button>
        </div>
      </div>
    `;

    // Criar overlay
    const overlay = document.createElement('div');
    overlay.className = 'modal-overlay';
    overlay.innerHTML = modalHtml;
    document.body.appendChild(overlay);

    // Adicionar estilos
    this.addModalStyles();

    // Adicionar event listeners
    overlay.addEventListener('click', (e) => {
      const target = e.target as HTMLElement;
      
      if (target.classList.contains('modal-overlay') || target.classList.contains('btn-cancel')) {
        document.body.removeChild(overlay);
        return;
      }

      const periodOption = target.closest('.period-option') as HTMLElement;
      if (periodOption) {
        const selectedPeriod = periodOption.dataset['value'];
        document.body.removeChild(overlay);
        this.exportDataWithPeriod(selectedPeriod!);
      }
    });
  }

  /**
   * 📊 Exportar dados com período selecionado
   */
  private exportDataWithPeriod(period: string): void {
    let dateFilters: any = {};
    
    // Definir filtros baseado no período selecionado
    switch (period) {
      case 'today':
        dateFilters = DateRangeShortcuts.today();
        break;
      case 'yesterday':
        dateFilters = DateRangeShortcuts.yesterday();
        break;
      case 'last7Days':
        dateFilters = DateRangeShortcuts.last7Days();
        break;
      case 'last30Days':
        dateFilters = DateRangeShortcuts.last30Days();
        break;
      case 'previousMonth':
        dateFilters = DateRangeShortcuts.previousMonth();
        break;        
      case 'currentMonth':
        dateFilters = DateRangeShortcuts.currentMonth();
        break;
      case 'currentYear':
        dateFilters = DateRangeShortcuts.currentYear();
        break;
      case 'all':
      default:
        dateFilters = {}; // Sem filtros de data
        break;
    }

    // Fazer a requisição com os filtros
    dateFilters

    this.fuelcontrollService.getFuelcontrolls(1, 100000, {startDate: dateFilters.date_start,endDate: dateFilters.date_end}).subscribe((response: any) => {
      console.log('Resposta da API:', response);
      const data = response.data;
      
      if (!data || data.length === 0) {
        this.snackNotifyService.warning('Nenhum dado encontrado para exportar no período selecionado');
        return;
      }
      
      // Converter dados para CSV
      const csv = this.convertToCSV(data);
      
      // Criar nome do arquivo com período
      const periodLabel = this.getPeriodLabel(period);
      const fileName = `fuelcontroll_${periodLabel}_${new Date().toISOString().split('T')[0]}.csv`;
      
      // Criar e baixar o arquivo CSV
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      this.snackNotifyService.info(`Dados exportados para CSV com sucesso (${data.length} registros)`, { duration: 4000 });
    });
  }

  /**
   * 🏷️ Obter label do período para nome do arquivo
   */
  private getPeriodLabel(period: string): string {
    const labels: {[key: string]: string} = {
      'today': 'hoje',
      'yesterday': 'ontem',
      'last7Days': 'ultimos_7_dias',
      'last30Days': 'ultimos_30_dias',
      'currentMonth': 'mes_atual',
      'previousMonth': 'mes_anterior',
      'currentYear': 'ano_atual',
      'all': 'todos_dados'
    };
    return labels[period] || 'periodo_customizado';
  }

  /**
   * 🎨 Adicionar estilos do modal
   */
  private addModalStyles(): void {
    if (document.getElementById('period-modal-styles')) return;

    const styles = document.createElement('style');
    styles.id = 'period-modal-styles';
    styles.textContent = `
      .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
      }
      
      .period-selection-modal {
        background: white;
        border-radius: 8px;
        padding: 24px;
        max-width: 500px;
        width: 90%;
        max-height: 80vh;
        overflow-y: auto;
      }
      
      .period-selection-modal h3 {
        margin: 0 0 20px 0;
        color: #333;
        font-size: 18px;
      }
      
      .period-options {
        display: grid;
        gap: 12px;
        margin-bottom: 20px;
      }
      
      .period-option {
        padding: 12px 16px;
        border: 2px solid #e0e0e0;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s ease;
      }
      
      .period-option:hover {
        border-color: #2196F3;
        background: #f5f5f5;
      }
      
      .option-label {
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }
      
      .option-description {
        font-size: 12px;
        color: #666;
      }
      
      .modal-actions {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
      }
      
      .btn-cancel {
        padding: 8px 16px;
        border: 1px solid #ddd;
        background: white;
        border-radius: 4px;
        cursor: pointer;
      }
      
      .btn-cancel:hover {
        background: #f5f5f5;
      }
    `;
    document.head.appendChild(styles);
  }

  /**
   * 📊 Converter array de objetos para formato CSV
   */
  private convertToCSV(data: any[]): string {
    if (!data || data.length === 0) return '';
    
    const headers = Array.from(new Set(data.flatMap(obj => Object.keys(obj))));
    const csvHeaders = headers.join(',');
    
    const csvRows = data.map(obj => {
      return headers.map(header => {
        const value = obj[header];
        if (value === null || value === undefined) return '';
        const stringValue = String(value);
        if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
          return `"${stringValue.replace(/"/g, '""')}"`;
        }
        return stringValue;
      }).join(',');
    });
    
    return [csvHeaders, ...csvRows].join('\n');
  }
}