import {
  Component,
  OnInit,
  AfterViewInit,
  OnDestroy,
  inject,
  PLATFORM_ID,
  signal
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import {
  ReleaseService,
  Release,
  DetectedOS
} from '../../services/release.service';
import { SeoService } from '../../services/seo.service';
import { ScrollAnimationService } from '../../services/scroll-animation.service';
import { AdSlotComponent } from '../../components/ad-slot/ad-slot.component';
import { getOsIconPath } from './os-icon.util';

@Component({
  selector: 'app-downloads',
  standalone: true,
  imports: [AdSlotComponent, TranslateModule],
  templateUrl: './downloads.component.html'
})
export class DownloadsComponent implements OnInit, AfterViewInit, OnDestroy {
  readonly releaseService = inject(ReleaseService);
  readonly releases = signal<Release[]>([]);
  readonly latestRelease = signal<Release | null>(null);
  readonly detectedOS = signal<DetectedOS>({
    key: 'linux',
    icon: '🐧',
    filePattern: /\.AppImage$/i,
    ymlFile: 'latest-linux.yml'
  });
  readonly recommendedUrl = signal<string | null>(null);
  readonly loading = signal(true);

  private readonly seoService = inject(SeoService);
  private readonly scrollAnimation = inject(ScrollAnimationService);
  private readonly platformId = inject(PLATFORM_ID);
  private readonly translate = inject(TranslateService);

  ngOnInit(): void {
    this.seoService.updateFromTranslations('pages.downloads.seo', {
      url: 'https://toju.app/downloads'
    });

    const os = this.releaseService.detectOS();

    this.detectedOS.set(os);

    this.releaseService.fetchReleases().then((releases) => {
      this.releases.set(releases);

      if (releases.length > 0) {
        const latestRelease = releases[0];
        const recommendedAsset = latestRelease.assets.find(
          (releaseAsset) => os.filePattern.test(releaseAsset.name) && !releaseAsset.name.toLowerCase().includes('server')
        );

        this.latestRelease.set(latestRelease);
        this.recommendedUrl.set(recommendedAsset?.browser_download_url ?? null);
      }

      this.loading.set(false);
    });
  }

  ngAfterViewInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      setTimeout(() => this.scrollAnimation.init(), 100);
    }
  }

  ngOnDestroy(): void {
    this.scrollAnimation.destroy();
  }

  isMetaFile(name: string): boolean {
    const lower = name.toLowerCase();

    return lower.endsWith('.yml') || lower.endsWith('.yaml') || lower.endsWith('.blockmap') || lower.endsWith('.json');
  }

  getOsIcon(name: string, size = 64): string {
    return getOsIconPath(name, size);
  }

  getDetectedOsLabel(): string {
    return this.translate.instant(`common.os.${this.detectedOS().key}`);
  }

  getAssetOSLabel(name: string): string {
    return this.translate.instant(`common.os.${this.releaseService.getAssetOSKey(name)}`);
  }

  formatDate(dateStr: string): string {
    try {
      return new Date(dateStr).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    } catch {
      return dateStr;
    }
  }
}
