import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class SessionNoticeService {
  private toastEl: HTMLElement | null = null;
  private toastBodyEl: HTMLElement | null = null;
  private toastHeaderEl: HTMLElement | null = null;
  private handling401 = false;
  private last401At = 0;

  constructor(
    private authService: AuthService,
    private router: Router,
    @Inject(PLATFORM_ID) private platformId: object
  ) {}

  async handleUnauthorized(): Promise<void> {
    if (!isPlatformBrowser(this.platformId)) return;

    const now = Date.now();
    if (this.handling401 && now - this.last401At < 3000) return;
    this.handling401 = true;
    this.last401At = now;

    await this.showToast('Sua sessão expirou. Faça login novamente.', 'danger');
    this.authService.logout();
    this.router.navigateByUrl('/login');

    setTimeout(() => {
      this.handling401 = false;
    }, 3000);
  }

  async handleForbidden(): Promise<void> {
    if (!isPlatformBrowser(this.platformId)) return;
    await this.showToast('Acesso restrito.', 'warning');
  }

  private ensureToast(): void {
    if (!isPlatformBrowser(this.platformId)) return;
    if (this.toastEl && this.toastBodyEl && this.toastHeaderEl) return;

    const doc = document;
    let container = doc.getElementById('lg-global-toast-container');
    if (!container) {
      container = doc.createElement('div');
      container.id = 'lg-global-toast-container';
      container.className = 'toast-container position-fixed top-0 end-0 p-3';
      container.style.zIndex = '10000';
      doc.body.appendChild(container);
    }

    const toast = doc.createElement('div');
    toast.className = 'toast text-bg-danger border-0 shadow';
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');

    const header = doc.createElement('div');
    header.className = 'toast-header border-bottom-0';

    const title = doc.createElement('strong');
    title.className = 'me-auto text-primary';
    title.textContent = 'LineGestão';

    const closeBtn = doc.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'btn-close';
    closeBtn.setAttribute('data-bs-dismiss', 'toast');
    closeBtn.setAttribute('aria-label', 'Fechar');

    header.appendChild(title);
    header.appendChild(closeBtn);

    const body = doc.createElement('div');
    body.className = 'toast-body bg-white rounded-bottom text-dark';

    toast.appendChild(header);
    toast.appendChild(body);
    container.appendChild(toast);

    this.toastEl = toast;
    this.toastBodyEl = body;
    this.toastHeaderEl = header;
  }

  private async showToast(message: string, variant: 'danger' | 'warning'): Promise<void> {
    if (!isPlatformBrowser(this.platformId)) return;
    this.ensureToast();
    if (!this.toastEl || !this.toastBodyEl || !this.toastHeaderEl) return;

    this.toastBodyEl.textContent = message;
    this.toastEl.classList.remove('text-bg-danger', 'text-bg-warning');
    this.toastEl.classList.add(variant === 'warning' ? 'text-bg-warning' : 'text-bg-danger');

    try {
      const bs = await import('bootstrap');
      const toastInstance = bs.Toast.getOrCreateInstance(this.toastEl, {
        autohide: true,
        delay: 3000
      });
      toastInstance.show();
    } catch (error) {
      console.error(error);
    }
  }
}
