import { Injectable, signal, inject, Injector } 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';
import { PlaylistService } from './playlist.service';

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

  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>): Promise<Canto> {
    const current = this.myCanti();
    let updated: Canto[];
    let targetCanto: Canto;

    if (canto.id && canto.id.startsWith('my_')) {
      // Update existing song
      updated = current.map(c => {
        if (c.id === canto.id) {
          targetCanto = {
            ...c,
            titolo: canto.titolo || c.titolo,
            testo: canto.testo || c.testo,
            accordi: canto.accordi !== undefined ? canto.accordi : c.accordi,
            autore: canto.autore !== undefined ? canto.autore : c.autore,
            link_youtube: canto.link_youtube !== undefined ? canto.link_youtube : c.link_youtube,
            id_momenti: canto.id_momenti || c.id_momenti
          };
          return targetCanto;
        }
        return c;
      });
      // Fallback if not found in list (should not happen normally)
      if (!updated.some(c => c.id === canto.id)) {
        const numericId = canto.id ? Number(canto.id.replace('my_', '')) : NaN;
        const idCanti = isNaN(numericId) ? Date.now() : numericId;
        targetCanto = {
          id: canto.id,
          id_canti: canto.id_canti || idCanti,
          titolo: canto.titolo || 'Senza Titolo',
          testo: canto.testo || '',
          accordi: canto.accordi,
          autore: canto.autore,
          link_youtube: canto.link_youtube,
          id_momenti: canto.id_momenti || []
        };
        updated.push(targetCanto);
      }
    } else {
      // Create new song
      targetCanto = {
        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 || []
      };
      updated = [...current, targetCanto];
    }

    this.myCanti.set(updated);
    await this._storage?.set('my-canti', updated);
    
    // Sincronizza automaticamente in background
    if (!this.playlistService) {
      this.playlistService = this.injector.get(PlaylistService);
    }
    this.playlistService.syncLocalDataToServer();

    const toast = await this.toastController.create({
      message: 'Canto salvato nei "Miei Canti"!',
      duration: 2000,
      color: 'success'
    });
    toast.present();

    return targetCanto!;
  }

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

    // Sincronizza automaticamente in background
    if (!this.playlistService) {
      this.playlistService = this.injector.get(PlaylistService);
    }
    this.playlistService.syncLocalDataToServer();
  }

  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();
  }
}
