import { Component, OnInit, inject, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule, ModalController, ToastController } from '@ionic/angular';
import * as QRCode from 'qrcode';

@Component({
  selector: 'app-identity-qr-modal',
  templateUrl: './identity-qr-modal.component.html',
  styleUrls: ['./identity-qr-modal.component.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule]
})
export class IdentityQrModalComponent implements OnInit {
  private modalCtrl = inject(ModalController);
  private toastCtrl = inject(ToastController);

  @Input() userUuid!: string;
  public qrCodeUrl: string = '';

  ngOnInit() {
    this.generateQr();
  }

  async generateQr() {
    try {
      this.qrCodeUrl = await QRCode.toDataURL(this.userUuid, {
        errorCorrectionLevel: 'H',
        margin: 2,
        width: 400,
        color: {
          dark: '#1e293b', // Slate 800 for premium dark aesthetic contrast
          light: '#ffffff'
        }
      });
    } catch (err) {
      console.error('Failed to generate QR Code:', err);
    }
  }

  async copyToClipboard() {
    try {
      await navigator.clipboard.writeText(this.userUuid);
      const toast = await this.toastCtrl.create({
        message: 'Codice copiato negli appunti!',
        duration: 2000,
        color: 'success',
        position: 'bottom'
      });
      await toast.present();
    } catch (err) {
      console.error('Failed to copy text:', err);
    }
  }

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