import { CommonModule } from '@angular/common';
import { Component, OnDestroy, OnInit, Input } from '@angular/core';

import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-page-topbar',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './page-topbar.component.html',
  styleUrls: ['./page-topbar.component.scss']
})
export class PageTopbarComponent implements OnInit, OnDestroy {
  @Input() eyebrow = 'Panel';
  @Input() description = '';

  currentUserName = 'Equipo';
  currentClock = new Date();
  private clockIntervalId: ReturnType<typeof setInterval> | null = null;

  constructor(private authService: AuthService) {}

  ngOnInit(): void {
    this.startClock();
    this.loadCurrentUser();
  }

  ngOnDestroy(): void {
    if (this.clockIntervalId) {
      clearInterval(this.clockIntervalId);
    }
  }

  get currentTimeLabel(): string {
    return new Intl.DateTimeFormat('es-MX', {
      hour: '2-digit',
      minute: '2-digit'
    }).format(this.currentClock);
  }

  get currentDateLabel(): string {
    return new Intl.DateTimeFormat('es-MX', {
      weekday: 'long',
      day: '2-digit',
      month: 'long',
      year: 'numeric'
    }).format(this.currentClock);
  }

  private loadCurrentUser(): void {
    this.authService.getProfile().subscribe({
      next: profile => {
        this.currentUserName = profile?.name?.trim() || 'Equipo';
      },
      error: () => {
        this.currentUserName = 'Equipo';
      }
    });
  }

  private startClock(): void {
    this.currentClock = new Date();
    this.clockIntervalId = setInterval(() => {
      this.currentClock = new Date();
    }, 1000);
  }
}
