import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
import { PWAService } from '../../services/mobile/pwa.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-pwa-notifications',
  standalone: true,
  imports: [CommonModule, MatButtonModule, MatIconModule, MatCardModule],
  template: `
    <!-- Notificação de Update Disponível -->
    <div 
      *ngIf="showUpdateNotification" 
      class="pwa-notification update-notification"
      [@slideIn]>
      <div class="notification-content">
        <mat-icon class="notification-icon">system_update</mat-icon>
        <div class="notification-text">
          <h4>Nova versão disponível!</h4>
          <p>Uma atualização da aplicação está pronta para ser instalada.</p>
        </div>
      </div>
      <div class="notification-actions">
        <button mat-button (click)="dismissUpdate()" class="dismiss-btn">
          Mais tarde
        </button>
        <button mat-raised-button color="primary" (click)="installUpdate()" class="action-btn">
          <mat-icon>download</mat-icon>
          Atualizar agora
        </button>
      </div>
    </div>

    <!-- Notificação de Instalação Disponível -->
    <div 
      *ngIf="showInstallNotification" 
      class="pwa-notification install-notification"
      [@slideIn]>
      <div class="notification-content">
        <mat-icon class="notification-icon">install_mobile</mat-icon>
        <div class="notification-text">
          <h4>Instalar aplicativo</h4>
          <p>Adicione este app à sua tela inicial para acesso rápido.</p>
        </div>
      </div>
      <div class="notification-actions">
        <button mat-button (click)="dismissInstall()" class="dismiss-btn">
          Não, obrigado
        </button>
        <button mat-raised-button color="accent" (click)="installApp()" class="action-btn">
          <mat-icon>add_to_home_screen</mat-icon>
          Instalar
        </button>
      </div>
    </div>

    <!-- Status PWA (apenas para debug) -->
    <div *ngIf="showDebugInfo" class="pwa-debug-info">
      <h5>🔧 Debug PWA</h5>
      <p><strong>PWA Suportado:</strong> {{ isPWASupported ? '✅' : '❌' }}</p>
      <p><strong>PWA Instalado:</strong> {{ isInstalledPWA ? '✅' : '❌' }}</p>
      <p><strong>Pode Instalar:</strong> {{ canInstall ? '✅' : '❌' }}</p>
      <p><strong>Update Disponível:</strong> {{ isUpdateAvailable ? '✅' : '❌' }}</p>
      
      <div class="debug-actions">
        <button mat-button (click)="checkForUpdate()" class="debug-btn">
          Verificar Update
        </button>
        <button mat-button (click)="forceInstallPrompt()" class="debug-btn">
          Forçar Install
        </button>
      </div>
    </div>
  `,
  styles: [`
    .pwa-notification {
      position: fixed;
      top: 80px;
      right: 20px;
      max-width: 400px;
      background: var(--surface);
      border: 1px solid var(--border-color);
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 9999;
      padding: 1rem;
      margin-bottom: 1rem;

      @media (max-width: 768px) {
        position: fixed;
        top: auto;
        bottom: 80px; /* Acima do mobile footer menu */
        left: 10px;
        right: 10px;
        max-width: none;
        margin: 0;
      }
    }

    .notification-content {
      display: flex;
      align-items: flex-start;
      gap: 1rem;
      margin-bottom: 1rem;

      .notification-icon {
        color: var(--primary-color);
        font-size: 24px;
        width: 24px;
        height: 24px;
        margin-top: 2px;
      }

      .notification-text {
        flex: 1;

        h4 {
          margin: 0 0 0.5rem 0;
          font-size: 1rem;
          font-weight: 500;
          color: var(--text-primary);
        }

        p {
          margin: 0;
          font-size: 0.875rem;
          color: var(--text-secondary);
          line-height: 1.4;
        }
      }
    }

    .notification-actions {
      display: flex;
      justify-content: flex-end;
      gap: 0.5rem;

      @media (max-width: 768px) {
        flex-direction: column-reverse;
        gap: 0.75rem;

        .action-btn {
          width: 100%;
        }

        .dismiss-btn {
          width: 100%;
        }
      }
    }

    .update-notification {
      border-left: 4px solid var(--primary-color);
      
      .notification-icon {
        color: var(--primary-color);
      }
    }

    .install-notification {
      border-left: 4px solid var(--accent-color);
      
      .notification-icon {
        color: var(--accent-color);
      }
    }

    .action-btn {
      .mat-icon {
        margin-right: 0.5rem;
        font-size: 18px;
        width: 18px;
        height: 18px;
      }
    }

    .pwa-debug-info {
      position: fixed;
      bottom: 20px;
      left: 20px;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 1rem;
      border-radius: 8px;
      font-size: 0.75rem;
      z-index: 10000;
      max-width: 300px;

      h5 {
        margin: 0 0 0.5rem 0;
        font-size: 0.875rem;
      }

      p {
        margin: 0.25rem 0;
      }

      .debug-actions {
        margin-top: 0.5rem;
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;

        .debug-btn {
          font-size: 0.7rem;
          padding: 0.25rem 0.5rem;
          min-width: auto;
          color: white;
          border: 1px solid rgba(255, 255, 255, 0.3);
        }
      }
    }

    /* Animação de entrada */
    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateX(100%);
      }
      to {
        opacity: 1;
        transform: translateX(0);
      }
    }

    .pwa-notification {
      animation: slideIn 0.3s ease-out;
    }
  `],
  animations: []
})
export class PWANotificationsComponent implements OnInit, OnDestroy {
  showUpdateNotification = false;
  showInstallNotification = false;
  
  // 🔧 DEBUG PWA - Painel de desenvolvimento
  // showDebugInfo = true;  // ✅ Habilitado para desenvolvimento/testes
  showDebugInfo = false;    // ✅ Desabilitado para produção (oculta painel de debug)

  private subscriptions: Subscription[] = [];

  constructor(private pwaService: PWAService) {}

  ngOnInit(): void {
    this.setupSubscriptions();
    this.loadInitialState();
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  /**
   * Configura as assinaturas dos observables
   */
  private setupSubscriptions(): void {
    // Monitora updates disponíveis
    const updateSub = this.pwaService.updateAvailable$.subscribe(available => {
      this.showUpdateNotification = available;
    });

    // Monitora prompt de instalação disponível
    const installSub = this.pwaService.installPromptAvailable$.subscribe(available => {
      this.showInstallNotification = available && !this.isInstalledPWA;
    });

    this.subscriptions.push(updateSub, installSub);
  }

  /**
   * Carrega estado inicial
   */
  private loadInitialState(): void {
    this.showUpdateNotification = this.pwaService.isUpdateAvailable;
    this.showInstallNotification = this.pwaService.isInstallPromptAvailable && !this.isInstalledPWA;
  }

  /**
   * Instala a atualização
   */
  async installUpdate(): Promise<void> {
    await this.pwaService.activateUpdate();
    this.showUpdateNotification = false;
  }

  /**
   * Descarta a notificação de update
   */
  dismissUpdate(): void {
    this.showUpdateNotification = false;
  }

  /**
   * Instala o app como PWA
   */
  async installApp(): Promise<void> {
    const installed = await this.pwaService.showInstallPrompt();
    if (installed) {
      this.showInstallNotification = false;
    }
  }

  /**
   * Descarta a notificação de instalação
   */
  dismissInstall(): void {
    this.showInstallNotification = false;
  }

  /**
   * Verifica por updates (debug)
   */
  async checkForUpdate(): Promise<void> {
    await this.pwaService.checkForUpdate();
  }

  /**
   * Força o prompt de instalação (debug)
   */
  async forceInstallPrompt(): Promise<void> {
    await this.pwaService.showInstallPrompt();
  }

  /**
   * Getters para template
   */
  get isPWASupported(): boolean {
    return this.pwaService.isPWASupported();
  }

  get isInstalledPWA(): boolean {
    return this.pwaService.isInstalledPWA();
  }

  get canInstall(): boolean {
    return this.pwaService.canInstall;
  }

  get isUpdateAvailable(): boolean {
    return this.pwaService.isUpdateAvailable;
  }
} 