import { Component, OnInit, OnDestroy, signal, computed, effect, inject, ElementRef, AfterViewInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertController, ToastController, GestureController } from '@ionic/angular';
import { CantiService, Canto } from '../../services/canti.service';
import { AudioEngineService } from '../../services/audio-engine.service';
import { LyricsParserService, ParsedSection } from '../../services/lyrics-parser.service';
import { ThemeService } from '../../services/theme.service';
import { SettingsService } from '../../services/settings.service';
import { ConnectivityService } from '../../services/connectivity.service';
import { PlaylistService } from '../../services/playlist.service';
import { YoutubePlayerService } from '../../services/youtube-player.service';
import { MyCantiService } from '../../services/my-canti.service';
import { ComunitaService } from '../../services/comunita.service';
import { StatsService } from '../../services/stats.service';

@Component({
  selector: 'app-player',
  templateUrl: './player.page.html',
  styleUrls: ['./player.page.scss'],
  standalone: false
})
export class PlayerPage implements OnInit, AfterViewInit, OnDestroy {
  public canto = signal<Canto | null>(null);
  public activeSongId = signal<string | null>(null);

  /** true = show chords (accordi mode), false = text only */
  public showChords = signal<boolean>(false);
  public showSensitivitySlider = signal<boolean>(false);

  /** Autoscroll standard */
  public isAutoscrolling = signal<boolean>(false);
  public autoscrollSpeed = signal<number>(2);
  private autoscrollTimer: any = null;

  /** Font size scale factor (1.0 = default) */
  public fontSize = signal<number>(1.0);

  /** Parsed sections for the current view mode */
  public parsedSections = computed<ParsedSection[]>(() => {
    const c = this.canto();
    if (!c) return [];

    let sections: ParsedSection[];
    // For local songs, if accordi is missing but testo has chords, use parseAccordi on testo
    const hasChordsInText = !c.accordi && c.testo?.includes('[');
    
    if ((this.showChords() && c.accordi) || (this.showChords() && hasChordsInText)) {
      sections = this.lyricsParser.parseAccordi(c.accordi || c.testo);
    } else {
      sections = this.lyricsParser.parseText(c.testo);
    }

    // CRITICAL FIX: If sections are empty but we have text, force a manual section
    if (sections.length === 0 && c.testo) {
      const fallbackLines = c.testo.split('\n')
        .filter(l => l.trim().length > 0)
        .map(l => ({
          text: l.trim(),
          segments: [{ text: l.trim() }]
        }));
      
      if (fallbackLines.length > 0) {
        sections = [{
          type: 'verse',
          lines: fallbackLines
        }];
      }
    }

    // Apply transposition if in chords mode
    if (this.showChords() && this.transposeAmount() !== 0) {
      return this.lyricsParser.transposeSections(sections, this.transposeAmount());
    }

    return sections;
  });

  public transposeAmount = signal<number>(0);

  public currentLineIndex = signal<number>(0);
  public math = Math;
  public youtubePlayerService = inject(YoutubePlayerService);
  private channel = new BroadcastChannel('karaoke_sync');

  private readonly MIN_FONT = 0.6;
  private readonly MAX_FONT = 5.0;
  private readonly FONT_STEP = 0.15;

  private initialPinchDistance: number | null = null;
  private initialFontSize: number = 1.0;

  private lastMatchedTranscript: string = '';

  // --- Logic State ---
  private lastAdvanceTimestamp: number = 0;      // For safety cooldown
  private readonly ADVANCE_COOLDOWN = 1500;      // 1.5 seconds min
  
  private wordsSpokenInCurrentLine: number = 0;
  private lastProcessedTranscript: string = '';
  private initialStartTime: number = 0;

  private route = inject(ActivatedRoute);
  public router = inject(Router);
  public cantiService = inject(CantiService);
  public audioEngine = inject(AudioEngineService);
  private lyricsParser = inject(LyricsParserService);
  private alertCtrl = inject(AlertController);
  private toastCtrl = inject(ToastController);
  public themeService = inject(ThemeService);
  public settingsService = inject(SettingsService);
  public connectivityService = inject(ConnectivityService);
  public playlistService = inject(PlaylistService);
  public comunitaService = inject(ComunitaService);
  private myCantiService = inject(MyCantiService);
  private statsService = inject(StatsService);
  private gestureCtrl = inject(GestureController);
  private el = inject(ElementRef);
  private sanitizer = inject(DomSanitizer);

  private songStartTime: number = 0;

  constructor() {
    // Sync mode from global settings
    effect(() => {
      this.showChords.set(this.settingsService.showChordsDefault());
    }, { allowSignalWrites: true });

    // Automatic advancement logic based on line detection
    effect(() => {
      const count = this.audioEngine.linesDetected();
      if (count > 0) {
        this.next();
      }
    });

    // Auto-scroll logic: keep active line in view
    effect(() => {
      const idx = this.currentLineIndex();
      // Wait for DOM update
      setTimeout(() => {
        const activeElem = document.querySelector('.lyric-line.active');
        if (activeElem) {
          activeElem.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);
    });

    effect(() => {
      const c = this.canto();
      if (c) {
        if (this.playlistService.autoPlayPlaylist()) {
          setTimeout(() => this.initPlayer(c.id), 500);
        }
      }
    });

    // Reactive song loading based on activeSongId and available canti lists
    effect(() => {
      const id = this.activeSongId();
      const allCanti = this.cantiService.canti();
      const myCantiList = this.myCantiService.myCanti();
      const comunitaCantiPers = this.comunitaService.comunitaCantiPersonali();

      if (id) {
        let found: any = null;
        if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
          found = comunitaCantiPers.find(c => c.id === id);
        }
        if (!found) {
          found = allCanti.find(c => c.id === id);
        }
        if (!found) {
          found = myCantiList.find(c => c.id === id);
        }
        if (!found) {
          found = comunitaCantiPers.find(c => c.id === id);
        }

        if (found) {
          const current = this.canto();
          // Avoid duplicate triggers for the same song
          if (!current || current.id !== found.id) {
            this.logPreviousSongTime();
            this.canto.set(found);
            this.songStartTime = Date.now();
            this.cantiService.getStorage()?.set('last_song_id', id);
            this.channel.postMessage({ type: 'SYNC_CANTO', id: found.id });

            // Set custom community transposition if active
            if (this.comunitaService.comunitaCode() && this.comunitaService.isFilterActive()) {
              const settings = this.comunitaService.comunitaCantiSettings();
              const songSetting = settings.find(s => s.id_canti === found.id_canti || s.id_canti === Number(found.id));
              if (songSetting && songSetting.tonalita !== undefined) {
                this.transposeAmount.set(songSetting.tonalita);
              } else {
                this.transposeAmount.set(0);
              }
            } else {
              this.transposeAmount.set(0);
            }
          }
        }
      }
    }, { allowSignalWrites: true });
  }

  ngAfterViewInit() {
    const gesture = this.gestureCtrl.create({
      el: this.el.nativeElement,
      direction: 'x',
      gestureName: 'swipe-song',
      canStart: (ev) => {
        // Prevent swipe when touching the bottom toolbar or other interactive elements
        const target = ev.event.target as HTMLElement;
        return !target.closest('ion-footer');
      },
      onEnd: (ev) => {
        if (Math.abs(ev.deltaX) > 60) {
          if (ev.deltaX > 0) {
            this.prevSong();
          } else {
            this.nextSong();
          }
        }
      }
    });
    gesture.enable();
  }


  private getAllLines(): any[] {
    const sections = this.parsedSections();
    const allLines: any[] = [];
    for (const s of sections) {
      for (const l of s.lines) {
        allLines.push(l);
      }
    }
    return allLines;
  }

  ngOnInit() {
    this.route.queryParams.subscribe(async params => {
      let id = params['id'];
      if (params['t']) {
        this.initialStartTime = parseInt(params['t'], 10);
      }
      if (!id) {
        const checkStorage = async () => {
          let storage = this.cantiService.getStorage();
          while (!storage) {
            await new Promise(resolve => setTimeout(resolve, 50));
            storage = this.cantiService.getStorage();
          }
          const storedId = await storage.get('last_song_id');
          if (storedId && !this.activeSongId()) {
            this.activeSongId.set(storedId);
          }
        };
        checkStorage();
      } else {
        this.activeSongId.set(id);
      }
    });
  }



  onTouchStart(event: TouchEvent) {
    if (event.touches.length === 2) {
      this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
      this.initialFontSize = this.fontSize();
    }
  }

  onTouchMove(event: TouchEvent) {
    if (event.touches.length === 2 && this.initialPinchDistance !== null) {
      event.preventDefault();
      const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
      const ratio = currentDistance / this.initialPinchDistance;
      let newSize = this.initialFontSize * ratio;
      newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
      if (Math.abs(newSize - this.fontSize()) > 0.01) {
        this.fontSize.set(newSize);
        this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
      }
    }
  }

  onTouchEnd() {
    this.initialPinchDistance = null;
  }

  private getDistance(t1: Touch, t2: Touch): number {
    return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
  }

  toggleChords() {
    this.showChords.update(v => !v);
    this.channel.postMessage({ type: 'SYNC_CHORDS', showChords: this.showChords() });
    this.transposeAmount.set(0);
  }

  transposeUp() {
    this.transposeAmount.update(v => v + 1);
    this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount: this.transposeAmount() });

    const c = this.canto();
    if (c) {
      this.statsService.updateSongSettings(c.id_canti, this.transposeAmount());
    }
  }

  transposeDown() {
    this.transposeAmount.update(v => v - 1);
    this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount: this.transposeAmount() });

    const c = this.canto();
    if (c) {
      this.statsService.updateSongSettings(c.id_canti, this.transposeAmount());
    }
  }

  zoomIn() {
    if (this.fontSize() < this.MAX_FONT) {
      this.fontSize.update(v => Math.min(v + this.FONT_STEP, this.MAX_FONT));
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
    }
  }

  zoomOut() {
    if (this.fontSize() > this.MIN_FONT) {
      this.fontSize.update(v => Math.max(v - this.FONT_STEP, this.MIN_FONT));
      this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
    }
  }

  toggleListening() {
    if (this.audioEngine.isListening()) {
      this.audioEngine.stopListening();
      this.showSensitivitySlider.set(false);
    } else {
      this.audioEngine.startListening();
      this.showSensitivitySlider.set(true);
    }
  }

  toggleSensitivitySlider(event: Event) {
    event.stopPropagation();
    this.showSensitivitySlider.update(v => !v);
  }

  onSensitivityChange(event: any) {
    this.audioEngine.sensitivity.set(event.detail.value);
  }

  handleSensitivityTouch(event: TouchEvent) {
    event.preventDefault();
    const touch = event.touches[0];
    const target = event.currentTarget as HTMLElement;
    const rect = target.getBoundingClientRect();
    
    // Calculate percentage based on Y position (bottom is 50%, top is 100%)
    const rawPercentage = 100 - ((touch.clientY - rect.top) / rect.height * 100);
    // Map 0-100 raw to 50-100 range
    let percentage = 50 + (rawPercentage * 0.5);
    percentage = Math.max(50, Math.min(100, Math.round(percentage)));
    
    this.audioEngine.sensitivity.set(percentage);
  }

  toggleAudio() {
    if (this.youtubePlayerService.currentCantoId() === this.canto()?.id) {
      this.youtubePlayerService.togglePlayPause();
    } else {
      const c = this.canto();
      if (c) {
        this.playlistService.autoPlayPlaylist.set(true);
        this.initPlayer(c.id);
      }
    }
  }

  stopVideo(event?: Event) {
    if (event) event.stopPropagation();
    this.youtubePlayerService.stop();
    this.playlistService.autoPlayPlaylist.set(false);
  }

  onSeek(event: any) {
    this.youtubePlayerService.seekTo(event.detail.value);
  }

  restart() {
    this.currentLineIndex.set(0);
    this.audioEngine.resetWordCount();
    this.youtubePlayerService.seekTo(0);
    this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });
  }

  next() {
    this.lastAdvanceTimestamp = Date.now();
    this.audioEngine.resetWordCount();

    const totalLines = this.getTotalLines();
    if (this.currentLineIndex() < totalLines - 1) {
      this.currentLineIndex.set(this.currentLineIndex() + 1);
      this.channel.postMessage({ type: 'SYNC_INDEX', index: this.currentLineIndex() });
    }
  }

  prev() {
    this.lastAdvanceTimestamp = Date.now();
    this.audioEngine.resetWordCount();
    if (this.currentLineIndex() > 0) {
      this.currentLineIndex.set(this.currentLineIndex() - 1);
      this.channel.postMessage({ type: 'SYNC_INDEX', index: this.currentLineIndex() });
    }
  }

  nextSong() {
    let list = this.playlistService.activeListIds();
    if (list.length === 0) {
      list = this.cantiService.canti().map(c => c.id);
    }
    
    const currentId = this.canto()?.id;
    if (!currentId) return;

    const index = list.indexOf(currentId);
    if (index >= 0 && index < list.length - 1) {
      const nextId = list[index + 1];
      this.router.navigate(['/player'], { queryParams: { id: nextId } });
    } else {
      this.playlistService.autoPlayPlaylist.set(false);
    }
  }

  prevSong() {
    let list = this.playlistService.activeListIds();
    if (list.length === 0) {
      list = this.cantiService.canti().map(c => c.id);
    }

    const currentId = this.canto()?.id;
    if (!currentId) return;

    const index = list.indexOf(currentId);
    if (index > 0) {
      const prevId = list[index - 1];
      this.router.navigate(['/player'], { queryParams: { id: prevId } });
    }
  }

  private goToSong(id: string) {
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { id },
      queryParamsHandling: 'merge'
    });
    this.restart();
  }

  getTotalLines(): number {
    return this.parsedSections().reduce((acc, s) => acc + s.lines.length, 0);
  }

  isActiveLine(sectionIdx: number, lineIdx: number): boolean {
    let flatIdx = 0;
    for (let s = 0; s < this.parsedSections().length; s++) {
      for (let l = 0; l < this.parsedSections()[s].lines.length; l++) {
        if (s === sectionIdx && l === lineIdx) {
          return flatIdx === this.currentLineIndex();
        }
        flatIdx++;
      }
    }
    return false;
  }

  async openDisplay() {
    const url = this.router.serializeUrl(
      this.router.createUrlTree(['/display'], { queryParams: { id: this.canto()?.id } })
    );
    const absoluteUrl = window.location.origin + window.location.pathname + url;
    const win = window.open(absoluteUrl, '_blank', 'width=1024,height=768');
    if (!win) {
      const alert = await this.alertCtrl.create({
        header: 'Proiezione TV',
        message: 'Il browser ha bloccato l\'apertura della finestra. Vuoi copiare il link da inviare alla TV?',
        buttons: [
          { text: 'Annulla', role: 'cancel' },
          { text: 'Copia Link', handler: () => { this.copyToClipboard(absoluteUrl); } }
        ]
      });
      await alert.present();
    }
  }

  async copyToClipboard(text: string) {
    try {
      await navigator.clipboard.writeText(text);
      const toast = await this.toastCtrl.create({
        message: 'Link copiato negli appunti!',
        duration: 2000,
        position: 'top',
        color: 'secondary'
      });
      await toast.present();
    } catch (err) {}
  }

  openYoutube() {
    const videoId = this.cantiService.getYoutubeId(this.canto()?.link_youtube);
    if (videoId) {
      window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
    }
  }

  private initPlayer(id: string) {
    if (!this.youtubePlayerService.isPlayerSupported()) {
      return;
    }
    const startT = this.initialStartTime;
    this.initialStartTime = 0; // Reset
    
    this.youtubePlayerService.setMediaSessionCallbacks(
      () => this.nextSong(),
      () => this.prevSong()
    );

    this.youtubePlayerService.initPlayer(
      id, 
      startT,
      () => {
        if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
          this.nextSong();
        } else {
          this.playlistService.autoPlayPlaylist.set(false);
        }
      },
      () => {
        if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
          setTimeout(() => this.nextSong(), 1000);
        } else {
          this.playlistService.autoPlayPlaylist.set(false);
        }
      }
    );
  }

  togglePlaylistSelection() {
    const c = this.canto();
    if (c) {
      this.playlistService.toggleSongSelection(c.id);
    }
  }

  getCommunitySongNumber(canto: any): string | null {
    if (!canto) return null;
    if (!this.comunitaService.comunitaCode() || !this.comunitaService.isFilterActive()) return null;
    const cantiInfo = this.comunitaService.comunitaCantiInfo();
    const info = cantiInfo.find(x => x.id_canti === canto.id_canti || x.id_canti === Number(canto.id));
    return info && info.num_canto ? info.num_canto.toString() : null;
  }

  toggleAutoscroll() {
    if (this.isAutoscrolling()) {
      this.stopAutoscroll();
    } else {
      this.startAutoscroll();
    }
  }

  startAutoscroll() {
    this.isAutoscrolling.set(true);
    if (this.autoscrollTimer) clearInterval(this.autoscrollTimer);
    
    const scrollEl = this.el.nativeElement.querySelector('.lyrics-container');
    if (!scrollEl) return;

    this.autoscrollTimer = setInterval(() => {
      if (!this.isAutoscrolling()) {
        clearInterval(this.autoscrollTimer);
        return;
      }
      const step = this.autoscrollSpeed() * 0.25;
      scrollEl.scrollTop += step;
    }, 40);
  }

  stopAutoscroll() {
    this.isAutoscrolling.set(false);
    if (this.autoscrollTimer) {
      clearInterval(this.autoscrollTimer);
      this.autoscrollTimer = null;
    }
  }

  increaseAutoscrollSpeed() {
    this.autoscrollSpeed.update(s => Math.min(10, s + 1));
  }

  decreaseAutoscrollSpeed() {
    this.autoscrollSpeed.update(s => Math.max(1, s - 1));
  }

  private logPreviousSongTime() {
    const c = this.canto();
    if (c && this.songStartTime > 0) {
      const timeSpent = (Date.now() - this.songStartTime) / 1000;
      this.statsService.logSongView(c.id_canti, timeSpent);
      this.songStartTime = 0;
    }
  }

  ngOnDestroy() {
    this.stopAutoscroll();
    this.logPreviousSongTime();
    this.audioEngine.stopListening();
    this.channel.close();
  }
}
