import { Component, Input, SimpleChanges, input } from '@angular/core';

import { TranslateModule } from '@ngx-translate/core';

import { IRemainingTime } from '../../../interface/theme.interface';

@Component({
  selector: 'app-sale-timer',
  imports: [TranslateModule],
  templateUrl: './sale-timer.html',
  styleUrl: './sale-timer.scss',
})
export class SaleTimer {
  @Input() startDate: string | null = null;
  @Input() endDate: string | null = null;
  readonly title = input<string | null>(null);

  public remainingTime: IRemainingTime | null = null;
  private timerInterval: ReturnType<typeof setInterval> | null = null;

  ngOnChanges(changes: SimpleChanges) {
    this.clearTimer();

    if (changes['startDate']?.currentValue && changes['endDate']?.currentValue) {
      this.startDate = this.parseDate(changes['startDate'].currentValue);
      this.endDate = this.parseDate(changes['endDate'].currentValue);

      if (this.startDate && this.endDate && new Date(this.endDate).getTime() > Date.now()) {
        this.updateTimer();

        this.timerInterval = setInterval(() => {
          this.updateTimer();
        }, 1000);
      }
    }
  }

  private updateTimer() {
    if (this.startDate && this.endDate) {
      const now = Date.now();
      const startDateTime = new Date(this.startDate).getTime();
      const endDateTime = new Date(this.endDate).getTime();

      if (now >= endDateTime) {
        this.remainingTime = {
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0,
        };
        this.clearTimer();
        return;
      }

      const targetDate = now < startDateTime ? startDateTime : endDateTime;
      this.calculateTimeDifference(targetDate);
    }
  }

  private calculateTimeDifference(targetDate: number) {
    const now = Date.now();
    const timeDiff = targetDate - now;

    this.remainingTime = {
      days: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
      hours: Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)),
      seconds: Math.floor((timeDiff % (1000 * 60)) / 1000),
    };
  }

  private parseDate(dateStr: string): string | null {
    try {
      // Split the input date by `-` to extract year, month, and day
      const parts = dateStr.split('-');
      if (parts.length === 3) {
        const year = parts[0];
        const month = parts[1].padStart(2, '0'); // Ensure month has two digits
        const day = parts[2].padStart(2, '0'); // Ensure day has two digits

        // Construct ISO-compliant date string
        const normalizedDate = `${year}-${month}-${day}`;
        const parsedDate = new Date(normalizedDate);

        return isNaN(parsedDate.getTime()) ? null : parsedDate.toISOString();
      }
    } catch (error) {
      console.error('🚀 ~ Date parsing error:', error);
    }
    return null;
  }

  private clearTimer() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }
    this.remainingTime = null;
  }

  ngOnDestroy() {
    this.clearTimer();
  }
}
