import {Component, inject, Input, OnInit, ViewChild} from '@angular/core'
import {ActionSheetController, IonTextarea} from '@ionic/angular'
import {IMessage} from '../../../models/IMessage'
import {AuthService} from '../../services/auth.service'
import {DatabaseService} from '../../services/database.service'

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.scss'],
})
export class MessageComponent implements OnInit {
  @ViewChild(IonTextarea)
  messageTextArea?: IonTextarea

  @Input()
  message: IMessage = {content: '', user: '', profile: '', displayName: '', date: Date.now()}

  @Input({required: true})
  floatLeft!: boolean

  @Input()
  skeleton = false

  @Input({required: true})
  channel!: string

  #actionSheetCtrl = inject(ActionSheetController)
  #authService = inject(AuthService)
  #dbService = inject(DatabaseService)

  userId = this.#authService.getUserUID()
  enableEditing = false

  constructor() {
  }

  ngOnInit() {
  }

  async presentActionSheet() {
    const actionSheet = await this.#actionSheetCtrl.create({
      buttons: [
        {
          text: 'Delete',
          role: 'destructive',
          icon: 'trash',
          handler: () => this.deleteMessage(),
        },
        {
          text: 'Edit',
          role: 'destructive',
          icon: 'create',
          handler: () => {
            this.enableEditing = true
            setTimeout(() => this.messageTextArea?.setFocus(), 500)
          },
        },
      ],
    })

    await actionSheet.present()
  }

  async saveEdit(): Promise<void> {
    this.enableEditing = false
    await this.#dbService.updateMessage(this.channel, this.message.id!, this.message)
  }

  async deleteMessage(): Promise<void> {
    this.#dbService.deleteMessage(this.channel, this.message.id!).then()
  }
}
