import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UsuariosService } from '../../services/usuarios.service';
import { DashboardService } from '../../services/dashboard.service';
import { QuestionarioService } from '../../services/questionario.service';
import { Questionario } from '../../models/questionario.model';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MateriaisService } from '../../services/materiais.service';
import { AuthService, User } from '../../services/auth.service';

@Component({
  selector: 'app-listar-usuarios',
  standalone: true,
  imports: [
    FormsModule,
    CommonModule,
    RouterModule,
  ],
  templateUrl: './dashboardUsuario.component.html',
  styleUrls: ['./dashboardUsuario.component.css']
})

export class DashboardUsuarioComponent implements OnInit {
  nivelHumor: number | null = null;
  comment: string = '';
  ultimosQuestionariosNaoRespondidos: Questionario[] = [];

  dicaDoDia: string = '';
  tituloDica: string = '';
  funcionarioId: number | null = null;

  buttonImages: string[] = [
    'assets/images/emojis5.png',
    'assets/images/emojis4.png',
    'assets/images/emojis3.png',
    'assets/images/emojis2.png',
    'assets/images/emojis1.png'
  ];

  constructor(
    private usuariosService: UsuariosService,
    private dashboardService: DashboardService,
    private materiaisService: MateriaisService,
    private authService: AuthService,
    private questionarioService: QuestionarioService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.funcionarioId = this.getFuncionarioIdLogado() ?? null;

    if (this.funcionarioId) {
      this.carregarUltimosNaoRespondidos(this.funcionarioId);
    }

    // Carrega a dica do dia
    this.materiaisService.listarMateriais().subscribe({
      next: (materiais) => {
        if (materiais.length === 0) return;

        const dia = new Date().getDate();
        const indiceDica = dia % materiais.length;

        const dicaSelecionada = materiais[indiceDica];
        this.dicaDoDia = dicaSelecionada.conteudo;
        this.tituloDica = dicaSelecionada.titulo;
      },
      error: (err) => {
        console.error('Erro ao carregar materiais de apoio:', err);
      }
    });
  }

  private getFuncionarioIdLogado(): number | undefined {
    let userId: number | undefined;
    this.authService.currentUser.subscribe((user) => {
      userId = user?.id;
    }).unsubscribe();
    return userId;
  }


  selectButton(index: number): void {
    this.nivelHumor = index + 1;
  }

  submitCheckIn(): void {
    if (this.nivelHumor === null || this.funcionarioId === null) return;

    const checkInData = {
      idFuncionario: this.funcionarioId,
      nivelHumor: this.nivelHumor,
      comentario: this.comment,
      dataHora: new Date().toISOString(),
    };

    this.dashboardService.saveCheckIn(checkInData).subscribe({
      next: () => {
        console.log('Check-in enviado com sucesso');
        this.nivelHumor = null;
        this.comment = '';
      },
      error: (err) => {
        console.error('Erro ao enviar o check-in', err);
      }
    });
  }

  private carregarUltimosNaoRespondidos(funcId: number): void {
    this.questionarioService.listarQuestionariosPorFuncionario(funcId).subscribe({
      next: (questionarios) => {
        const naoRespondidos = questionarios
          .filter(q => !q.respondido)
          .sort((a, b) => new Date(b.dataValidade!).getTime() - new Date(a.dataValidade!).getTime());

        this.ultimosQuestionariosNaoRespondidos = naoRespondidos.slice(0, 3);
      },
      error: (err) => {
        console.error('Erro ao buscar questionários', err);
      }
    });
  }

  irParaListagem(): void {
    this.router.navigate(['/listar']);
  }
}
