import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';

import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { TitleService } from '../../shared/services/theme/title.service';
import { HeaderActionsService } from '../../shared/services/header-actions.service';
import { GenericCardComponent } from '../../shared/components/generic-card/generic-card.component';
import { GenericDetailsModalComponent } from '../../shared/components/generic-details-modal/generic-details-modal.component';
import { GenericConnectionModalComponent } from '../../shared/components/generic-connection-modal/generic-connection-modal.component';
import { IntegrationService } from './services/integration.service';
import { 
  Integration, 
  IntegrationFilter, 
  IntegrationStatus, 
  IntegrationCategory,
  GenericCard 
} from './interfaces/integration.interface';
import { GenericModalData, ConnectionModalData } from '../../shared/interfaces/generic-modal.interface';

@Component({
  selector: 'app-integration',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    GenericCardComponent,
    MatButtonModule,
    MatIconModule
  ],
  templateUrl: './integration.component.html',
  styleUrl: './integration.component.scss'
})
export class IntegrationComponent implements OnInit {
  integrations: Integration[] = [];
  filteredCards: GenericCard[] = [];
  isLoading = true;

  // Propriedades para os filtros customizados
  searchTerm = '';
  statusFilter: 'all' | IntegrationStatus | '' = '';

  currentFilter: IntegrationFilter = {
    search: '',
    status: 'all',
    category: IntegrationCategory.ALL
  };

  categories = [
    { label: 'Todas as integrações', value: IntegrationCategory.ALL, count: 0 },
    { label: 'Cadastros', value: IntegrationCategory.CADASTROS, count: 0 },
    { label: 'Rastreadores', value: IntegrationCategory.RASTREADORES, count: 0 },
    { label: 'Combustíveis', value: IntegrationCategory.COMBUSTIVEIS, count: 0 },
    { label: 'DMS', value: IntegrationCategory.DMS, count: 0 },
    { label: 'TMS', value: IntegrationCategory.TMS, count: 0 },
    { label: 'ERP', value: IntegrationCategory.ERP, count: 0 },
    { label: 'RPA', value: IntegrationCategory.RPA, count: 0 },
    { label: 'RMS', value: IntegrationCategory.RMS, count: 0 }
  ];

  constructor(
    private integrationService: IntegrationService,
    private dialog: MatDialog,
    private titleService: TitleService,
    private headerActionsService: HeaderActionsService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.titleService.setTitle('Integrações');
    this.configureHeader();
    this.loadIntegrations();
  }

  private configureHeader(): void {
    this.headerActionsService.setDomainConfig({
      domain: 'integrations',
      title: 'Integrações',
      recordCount: this.getConnectedCount(),
      actions: []
    });
  }

  private updateHeaderRecordCount(): void {
    this.headerActionsService.updateRecordCount(this.getConnectedCount());
  }

  loadIntegrations(): void {
    this.isLoading = true;
    
    // Converter filtros para o formato esperado pelo service
    const filters: { [key: string]: string } = {};
    if (this.currentFilter.search) filters['search'] = this.currentFilter.search;
    if (this.currentFilter.isEnabled !== undefined) filters['isEnabled'] = this.currentFilter.isEnabled.toString();
    if (this.currentFilter.status && this.currentFilter.status !== 'all') filters['status'] = this.currentFilter.status;
    if (this.currentFilter.category && this.currentFilter.category !== 'all') filters['category'] = this.currentFilter.category;
    
    // Usar o novo service padrão com paginação
    this.integrationService.getIntegrations(1, 30, filters)
      .subscribe({
        next: (response) => {
          this.integrations = response.data;
          this.updateCategoryCounts();
          this.updateFilteredCards();
          this.updateHeaderRecordCount();
          this.isLoading = false;
          this.cdr.detectChanges();
          
          console.log('✅ Integrações carregadas do backend:', response);
        },
        error: (error) => {
          console.error('❌ Erro ao carregar integrações:', error);
          this.isLoading = false;
          this.cdr.detectChanges();
        }
      });
  }

  private mapIntegrationToCard(integration: Integration): GenericCard {
    const status = this.getIntegrationStatus(integration);
    const category = this.getIntegrationCategory(integration.type);
    
    return {
      id: integration.id,
      title: integration.type,
      description: this.getIntegrationDescription(integration.type),
      status,
      statusLabel: this.getStatusLabel(status),
      iconClass: this.getIntegrationIcon(integration.type),
      category: this.getCategoryLabel(category),
      actions: this.getCardActions(status)
    };
  }

  private getIntegrationStatus(integration: Integration): 'connected' | 'error' | 'disconnected' | 'active' | 'inactive' {
    // Se não está habilitada ou foi deletada
    if (!integration.isEnabled || integration.deletedAt) {
      return 'disconnected';
    }
    
    // Verificar status no cache se disponível
    if (integration.cache && integration.cache['lastRunAt']) {
      // Se tem dados de cache recentes, está conectada
      const lastRun = new Date(integration.cache['lastRunAt']);
      const now = new Date();
      const diffHours = (now.getTime() - lastRun.getTime()) / (1000 * 60 * 60);
      
      // Se executou nas últimas 24 horas, considerar conectado
      if (diffHours <= 24) {
        return 'connected';
      }
    }
    
    // Se não tem cache ou cache muito antigo
    if (!integration.cache || !integration.cache['lastRunAt']) {
      return 'error';
    }
    
    return 'connected';
  }

  private getIntegrationCategory(type: string): IntegrationCategory {
    const categoryMap: Record<string, IntegrationCategory> = {
      // Novos tipos da API
      'Meli': IntegrationCategory.TMS,
      'SasCar': IntegrationCategory.RASTREADORES,
      'BrasilCredit': IntegrationCategory.CADASTROS,
      
      // Tipos existentes
      'BrasilCredito': IntegrationCategory.CADASTROS,
      'IdWall': IntegrationCategory.CADASTROS,
      'T4S Tecnologia': IntegrationCategory.RASTREADORES,
      'Geotab': IntegrationCategory.RASTREADORES,
      'Sascar': IntegrationCategory.RASTREADORES,
      'Emnify': IntegrationCategory.RASTREADORES,
      'Fleet Complete': IntegrationCategory.RASTREADORES,
      'Viasat': IntegrationCategory.RASTREADORES,
      'Onixsat': IntegrationCategory.RASTREADORES,
      'ProFrotas': IntegrationCategory.COMBUSTIVEIS,
      'Pluxee': IntegrationCategory.COMBUSTIVEIS,
      'Ticket Car': IntegrationCategory.COMBUSTIVEIS,
      'Sem Parar': IntegrationCategory.COMBUSTIVEIS,
      'DealerSocket': IntegrationCategory.DMS,
      'Omnilogic': IntegrationCategory.TMS
    };
    return categoryMap[type] || IntegrationCategory.ALL;
  }

  private getIntegrationDescription(type: string): string {
    const descriptions: Record<string, string> = {
      // Novos tipos da API
      'Meli': 'Integração com Mercado Livre para coleta de rotas e otimização logística',
      'SasCar': 'Sistema de rastreamento SasCar para monitoramento de veículos',
      'BrasilCredit': 'Sistema de consulta de dados veiculares e pessoais',
      
      // Tipos existentes
      'BrasilCredito': 'Consulta de dados veiculares e pessoais',
      'IdWall': 'Verificação de identidade e dados cadastrais',
      'T4S Tecnologia': 'Soluções de rastreamento e telemetria veicular',
      'Geotab': 'Plataforma de gestão de frota e rastreamento',
      'Sascar': 'Rastreamento e monitoramento de veículos',
      'Emnify': 'Chips Universais que aceitam qualquer operadora para rastreamento',
      'ProFrotas': 'Gerenciamento de combustível para frota própria e agregados',
      'Pluxee': 'Sistema de gestão de combustível e benefícios',
      'DealerSocket': 'Sistema de gerenciamento de concessionárias',
      'Omnilogic': 'Soluções logísticas integradas e gestão de rotas',
      'Fleet Complete': 'Rastreamento completo de frota com análise de desempenho',
      'Ticket Car': 'Sistema de pagamento para combustível e pedágios',
      'Viasat': 'Comunicação via satélite para frotas remotas',
      'Onixsat': 'Rastreamento por satélite com cobertura nacional',
      'Sem Parar': 'Pagamento automático para pedágios e combustível'
    };
    return descriptions[type] || 'Integração personalizada para gestão de frota';
  }

  private getIntegrationIcon(type: string): string {
    const icons: Record<string, string> = {
      // Novos tipos da API
      'Meli': 'fas fa-shopping-cart',
      'SasCar': 'fas fa-car',
      'BrasilCredit': 'fas fa-credit-card',
      
      // Tipos existentes
      'BrasilCredito': 'fas fa-credit-card',
      'IdWall': 'fas fa-shield-alt',
      'T4S Tecnologia': 'fas fa-satellite-dish',
      'Geotab': 'fas fa-map-marked-alt',
      'Sascar': 'fas fa-car',
      'Emnify': 'fas fa-sim-card',
      'ProFrotas': 'fas fa-gas-pump',
      'Pluxee': 'fas fa-fuel-pump',
      'DealerSocket': 'fas fa-building',
      'Omnilogic': 'fas fa-route',
      'Fleet Complete': 'fas fa-tachometer-alt',
      'Ticket Car': 'fas fa-ticket-alt',
      'Viasat': 'fas fa-satellite',
      'Onixsat': 'fas fa-broadcast-tower',
      'Sem Parar': 'fas fa-credit-card'
    };
    return icons[type] || 'fas fa-plug';
  }

  private getStatusLabel(status: string): string {
    const labels: Record<string, string> = {
      'connected': 'Conectado',
      'error': 'Erro',
      'disconnected': 'Não conectado'
    };
    return labels[status] || status;
  }

  private getCategoryLabel(category: IntegrationCategory): string {
    const labels: Record<IntegrationCategory, string> = {
      [IntegrationCategory.ALL]: 'Geral',
      [IntegrationCategory.CADASTROS]: 'Cadastros',
      [IntegrationCategory.RASTREADORES]: 'Rastreadores',
      [IntegrationCategory.COMBUSTIVEIS]: 'Combustíveis',
      [IntegrationCategory.DMS]: 'DMS',
      [IntegrationCategory.TMS]: 'TMS',
      [IntegrationCategory.ERP]: 'ERP',
      [IntegrationCategory.RPA]: 'RPA',
      [IntegrationCategory.RMS]: 'RMS'
    };
    return labels[category] || 'Geral';
  }

  private getCardActions(status: string) {
    const actions = [];
    
    if (status === 'connected') {
      actions.push({
        label: 'Reconectar',
        action: 'reconnect',
        type: 'primary' as const,
        icon: 'settings'
      });
    } else if (status === 'error') {
      actions.push({
        label: 'Reconectar',
        action: 'reconnect',
        type: 'danger' as const,
        icon: 'settings'
      });
    } else {
      actions.push({
        label: 'Conectar',
        action: 'connect',
        type: 'connect' as const,
        icon: 'bolt'
      });
    }

    actions.push({
      label: 'Ver detalhes',
      action: 'details',
      type: 'secondary' as const,
      icon: 'arrow_forward'
    });

    return actions;
  }

  onFilterChange(): void {
    this.updateFilteredCards();
  }

  onCategoryFilter(category: IntegrationCategory): void {
    this.currentFilter.category = category;
    this.updateFilteredCards();
  }

  private updateFilteredCards(): void {
    let filtered = this.integrations.map(integration => this.mapIntegrationToCard(integration));

    // Filtro por busca
    if (this.currentFilter.search) {
      const search = this.currentFilter.search.toLowerCase();
      filtered = filtered.filter(card => 
        card.title.toLowerCase().includes(search) ||
        card.description.toLowerCase().includes(search)
      );
    }

    // Filtro por status
    if (this.currentFilter.status && this.currentFilter.status !== 'all') {
      filtered = filtered.filter(card => card.status === this.currentFilter.status);
    }

    // Filtro por categoria
    if (this.currentFilter.category && this.currentFilter.category !== IntegrationCategory.ALL) {
      filtered = filtered.filter(card => {
        const integration = this.integrations.find(i => i.id === card.id);
        return integration && this.getIntegrationCategory(integration.type) === this.currentFilter.category;
      });
    }

    this.filteredCards = filtered;
  }

  private updateCategoryCounts(): void {
    this.categories.forEach(category => {
      if (category.value === IntegrationCategory.ALL) {
        category.count = this.integrations.length;
      } else {
        category.count = this.integrations.filter(integration => 
          this.getIntegrationCategory(integration.type) === category.value
        ).length;
      }
    });
  }

  getConnectedCount(): number {
    return this.integrations.filter(integration => 
      integration.isEnabled && !integration.deletedAt
    ).length;
  }

  getTotalCount(): number {
    return this.integrations.length;
  }

  getStatusCount(status: string): number {
    return this.integrations.filter(integration => {
      const integrationStatus = this.getIntegrationStatus(integration);
      return integrationStatus === status;
    }).length;
  }

  onCardAction(event: { action: string; card: GenericCard }): void {
    const { action, card } = event;
    const integration = this.integrations.find(i => i.id === card.id);

    if (!integration) return;

    switch (action) {
      case 'details':
        this.openDetailsModal(integration);
        break;
      case 'connect':
      case 'reconnect':
        this.openConnectionModal(integration, action === 'reconnect');
        break;
    }
  }

  private openDetailsModal(integration: Integration): void {
    const modalData: GenericModalData = {
      title: integration.type,
      subtitle: 'Detalhes da integração',
      data: {
        type: integration.type,
        description: this.getIntegrationDescription(integration.type),
        status: this.getIntegrationStatus(integration),
        lastSync: integration.updatedAt
      },
      fields: [
        { key: 'status', label: 'Status', type: 'status' },
        { key: 'description', label: 'Descrição', type: 'description' },
        { key: 'lastSync', label: 'Última Sincronização', type: 'date' }
      ]
    };

    this.dialog.open(GenericDetailsModalComponent, {
      width: '450px',
      maxWidth: '90vw',
      panelClass: 'custom-modal-panel',
      backdropClass: 'custom-modal-backdrop',
      hasBackdrop: false,
      data: modalData
    });
  }

  private openConnectionModal(integration: Integration, isReconnect: boolean): void {
    const modalData: ConnectionModalData = {
      title: `${isReconnect ? 'Reconectar' : 'Conectar'} ${integration.type}`,
      subtitle: 'Preencha as informações necessárias para estabelecer a conexão',
      isReconnect,
      fields: [
        {
          key: 'apiKey',
          label: 'Chave da API',
          type: 'text',
          required: true,
          placeholder: 'Cole sua chave de API aqui'
        },
        {
          key: 'endpoint',
          label: 'Endpoint (opcional)',
          type: 'url',
          required: false,
          placeholder: 'https://api.exemplo.com'
        }
      ]
    };

    const dialogRef = this.dialog.open(GenericConnectionModalComponent, {
      width: '500px',
      maxWidth: '90vw',
      panelClass: 'custom-modal-panel',
      backdropClass: 'custom-modal-backdrop',
      hasBackdrop: false,
      data: modalData
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result && result.action === 'connect') {
        this.handleConnection(integration, result.data, isReconnect);
      }
    });
  }

  private handleConnection(integration: Integration, connectionData: any, isReconnect: boolean): void {
    const serviceCall = isReconnect 
      ? this.integrationService.reconnectIntegration(integration.id, connectionData)
      : this.integrationService.connectIntegration(integration.id, connectionData);

    serviceCall.subscribe({
      next: (updatedIntegration) => {
        // Atualizar a integração na lista
        const index = this.integrations.findIndex(i => i.id === integration.id);
        if (index !== -1) {
          this.integrations[index] = updatedIntegration;
          this.updateFilteredCards();
        }
        // Aqui você poderia adicionar uma notificação de sucesso
      },
      error: (error) => {
        console.error('Erro ao conectar integração:', error);
        // Aqui você poderia adicionar uma notificação de erro
      }
    });
  }

  onSearchChange(): void {
    this.currentFilter.search = this.searchTerm;
    this.updateFilteredCards();
  }

  onStatusChange(): void {
    this.currentFilter.status = this.statusFilter || 'all';
    this.updateFilteredCards();
  }

  getErrorCount(): number {
    return this.integrations.filter(integration => 
      integration.deletedAt !== null
    ).length;
  }

  getDisconnectedCount(): number {
    return this.integrations.filter(integration => 
      !integration.isEnabled || integration.deletedAt
    ).length;
  }


}
