import { Component, Input, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { IonContent, ModalController } from '@ionic/angular';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';

@Component({
  selector: 'app-report-discussion',
  templateUrl: './report-discussion.page.html',
  styleUrls: ['./report-discussion.page.scss'],
  standalone: false
})
export class ReportDiscussionPage implements OnInit {

  @Input() reportId: any;

  @ViewChild('content') content!: IonContent;

  messages: any[] = [];
  newMessage: string = '';
  currentUserId: any;
  loading = true;
  sending = false;

  constructor(
    private modalCtrl: ModalController,
    private ichambaService: IchambaService,
    private authService: AuthService,
    private alertService: AlertService,
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnInit() {
    this.currentUserId = this.authService.userId;
    this.loadMessages();
  }

  loadMessages() {
    this.loading = true;
    this.ichambaService.getReportDiscussion(this.reportId).subscribe({
      next: data => {
        this.messages = data;
        this.loading = false;
        this.cdr.detectChanges();
        setTimeout(() => this.content.scrollToBottom(300), 100);
      },
      error: () => {
        this.loading = false;
        this.cdr.detectChanges();
      }
    });
  }

  sendMessage() {
    const text = this.newMessage.trim();
    if (!text || this.sending) return;
    this.newMessage = '';
    this.sending = true;
    this.ichambaService.sendReportMessage(this.reportId, text).subscribe({
      next: (msg: any) => {
        this.messages.push(msg);
        this.sending = false;
        this.cdr.detectChanges();
        setTimeout(() => this.content.scrollToBottom(300), 100);
      },
      error: () => {
        this.sending = false;
        this.alertService.presentToast('No se pudo enviar el mensaje.');
      }
    });
  }

  attachPhoto() {
    // TODO: implementar captura y envío de foto
  }

  dismiss() {
    this.modalCtrl.dismiss();
  }
}
