import { Component, inject } from '@angular/core';
import { ThemeService } from '../../services/theme.service';
import { SettingsService } from '../../services/settings.service';
import { CantiService } from '../../services/canti.service';
import { ConnectivityService } from '../../services/connectivity.service';
import { SwUpdate } from '@angular/service-worker';
import { ToastController, ModalController, AlertController } from '@ionic/angular';
import { VERSION } from '../../version';
import { PlaylistService } from '../../services/playlist.service';
import { Router } from '@angular/router';

import { MyCantiService } from '../../services/my-canti.service';
import { CantiLettureService } from '../../services/canti-letture.service';
import { ComunitaService } from '../../services/comunita.service';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-settings',
  templateUrl: './settings.page.html',
  styleUrls: ['./settings.page.scss'],
  standalone: false
})
export class SettingsPage {
  public myCantiService = inject(MyCantiService);
  public themeService = inject(ThemeService);
  public settingsService = inject(SettingsService);
  public cantiService = inject(CantiService);
  public connectivityService = inject(ConnectivityService);
  public playlistService = inject(PlaylistService);
  public cantiLettureService = inject(CantiLettureService);
  public comunitaService = inject(ComunitaService);
  private swUpdate = inject(SwUpdate);
  private toastCtrl = inject(ToastController);
  private modalCtrl = inject(ModalController);
  private alertCtrl = inject(AlertController);
  private router = inject(Router);

  public version = VERSION;
  public contactEmail = environment.contactEmail;
  public appName = environment.appName;
  public showIosInstructions = false;

  constructor() {}

  async installApp() {
    await this.settingsService.installPwa();
  }

  toggleIosInstructions() {
    this.showIosInstructions = !this.showIosInstructions;
  }

  onModeChange(event: any) {
    this.settingsService.setShowChordsDefault(event.detail.value === 'chords');
  }

  onMassChange(event: any) {
    this.cantiLettureService.setSelectedMass(event.detail.value);
  }

  async fullRefresh() {
    // 1. Refresh JSON data
    this.cantiService.refresh();
    
    // 2. Refresh liturgical readings JSON
    try {
      await this.cantiLettureService.fetchData();
    } catch (err) {
      console.error('Failed to refresh liturgical readings:', err);
    }

    // 3. Refresh community data if a code is active
    const comunitaCode = this.comunitaService.comunitaCode();
    if (comunitaCode) {
      try {
        await this.comunitaService.setComunitaCode(comunitaCode);
      } catch (err) {
        console.error('Failed to refresh community data:', err);
      }
    }

    // 4. Check for Service Worker updates
    if (this.swUpdate.isEnabled) {
      try {
        const updateFound = await this.swUpdate.checkForUpdate();
        if (updateFound) {
          const toast = await this.toastCtrl.create({
            message: 'Nuova versione disponibile! Aggiornamento in corso...',
            duration: 2000,
            color: 'secondary'
          });
          await toast.present();
          
          setTimeout(() => {
            window.location.reload();
          }, 2000);
          return;
        }
      } catch (err) {
        console.error('Failed to check for updates', err);
      }
    }

    const toast = await this.toastCtrl.create({
      message: 'Dati aggiornati correttamente!',
      duration: 2000,
      color: 'success'
    });
    await toast.present();
  }
}
