import { Injectable, signal, inject } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import { Canto, CantiService } from './canti.service';
import { ToastController } from '@ionic/angular';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class MyCantiService {
  private storage = inject(Storage);
  private cantiService = inject(CantiService);
  private toastController = inject(ToastController);

  private _storage: Storage | null = null;
  public myCanti = signal<Canto[]>([]);

  constructor() {
    this.init();
  }

  async init() {
    this._storage = this.cantiService.getStorage();
    if (!this._storage) {
      // If CantiService hasn't initialized storage yet, wait a bit
      setTimeout(() => this.init(), 500);
      return;
    }
    const saved = await this._storage.get('my-canti');
    if (saved) {
      this.myCanti.set(saved);
    }
  }

  async saveCanto(canto: Partial<Canto>) {
    const current = this.myCanti();
    const newCanto: Canto = {
      id: `my_${Date.now()}`,
      id_canti: Date.now(), // Fake ID for internal logic
      titolo: canto.titolo || 'Senza Titolo',
      testo: canto.testo || '',
      accordi: canto.accordi,
      autore: canto.autore,
      link_youtube: canto.link_youtube,
      id_momenti: canto.id_momenti || []
    };

    const updated = [...current, newCanto];
    this.myCanti.set(updated);
    await this._storage?.set('my-canti', updated);
    
    const toast = await this.toastController.create({
      message: 'Canto salvato nei "Miei Canti"!',
      duration: 2000,
      color: 'success'
    });
    toast.present();
  }

  async deleteCanto(id: string) {
    const updated = this.myCanti().filter(c => c.id !== id);
    this.myCanti.set(updated);
    await this._storage?.set('my-canti', updated);
  }

  async sendAllMyCanti() {
    const data = {
      version: new Date().toISOString(),
      canti: this.myCanti()
    };
    
    const body = JSON.stringify(data, null, 2);
    const subject = `Proposta Collection Canti: ${this.myCanti().length} brani`;
    const mailtoUrl = `mailto:${environment.contactEmail}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;

    window.location.href = mailtoUrl;

    const toast = await this.toastController.create({
      message: 'Email generata con il JSON dei tuoi canti.',
      duration: 3000,
      color: 'secondary'
    });
    toast.present();
  }
}
