import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
  signal,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { animate, style, transition, trigger } from '@angular/animations';
import { interval, Subscription, takeWhile } from 'rxjs';
import { AnimatedNumberComponent } from '@blackjack/components/animated-number/animated-number.component';

@Component({
  selector: 'app-debt-dialog',
  standalone: true,
  imports: [CommonModule, AnimatedNumberComponent],
  template: `
    <div *ngIf="visible" [@fadeInOut] class="modal-bg" style="z-index: 1000; position: fixed;">
      <div class="modal-card" [@cardAnimation]>
        <h2 class="modal-heading text-accent-red">WARNUNG!</h2>
        <p class="py-2 text-text-secondary mb-4">
          Du hast nicht genug Geld für den Double Down. Du bist jetzt im Minus und schuldest uns
          <app-animated-number [value]="amount" [duration]="0.5"></app-animated-number>.
        </p>
        <p class="py-2 text-accent-red mb-4 font-bold">
          Liefer das Geld sofort an den Dead Drop oder es wird unangenehme Konsequenzen geben!
        </p>
        <div
          class="bg-deep-blue-light/50 rounded-lg p-5 mb-6 shadow-inner border border-deep-blue-light/30"
        >
          <div class="grid grid-cols-2 gap-4">
            <div class="text-text-secondary">Schulden:</div>
            <div class="font-medium text-right text-accent-red">
              <app-animated-number [value]="amount" [duration]="0.5"></app-animated-number>
            </div>
          </div>
        </div>
        <div class="text-center mb-6">
          <div
            class="text-8xl font-bold text-accent-red"
            [class.animate-pulse]="timeLeft() <= 10"
            [class.animate-bounce]="timeLeft() <= 5"
            [@countdown]="timeLeft()"
          >
            {{ timeLeft() }}
          </div>
          <div class="text-text-secondary mt-2">Sekunden verbleibend</div>
        </div>
        @if (timeLeft() === 0) {
          <div class="text-center mb-6">
            <div class="relative">
              <div class="absolute inset-0 bg-accent-red/20 blur-xl rounded-full"></div>
              <div
                class="relative bg-gradient-to-b from-accent-red to-red-900 p-8 rounded-lg border-2 border-accent-red shadow-lg"
              >
                <div class="flex items-center justify-center gap-4 mb-4">
                  <svg
                    class="w-12 h-12 text-accent-red animate-[spin_2s_linear_infinite]"
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                  >
                    <path
                      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"
                    />
                  </svg>
                  <span
                    class="text-4xl font-black tracking-wider text-white animate-[pulse_1s_ease-in-out_infinite]"
                  >
                    ZEIT ABGELAUFEN
                  </span>
                  <svg
                    class="w-12 h-12 text-accent-red animate-[spin_2s_linear_infinite]"
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                  >
                    <path
                      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"
                    />
                  </svg>
                </div>
                <div
                  class="text-2xl font-bold text-white/90 tracking-wider animate-[pulse_1s_ease-in-out_infinite]"
                >
                  KONSEQUENZEN FOLGEN
                </div>
              </div>
            </div>
          </div>
        }
        <button type="button" (click)="closeDialog()" class="button-primary w-full py-2">
          Verstanden
        </button>
      </div>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('150ms ease-out', style({ opacity: 1 })),
      ]),
      transition(':leave', [animate('150ms ease-in', style({ opacity: 0 }))]),
    ]),
    trigger('cardAnimation', [
      transition(':enter', [
        style({ opacity: 0, transform: 'scale(0.95)' }),
        animate('200ms ease-out', style({ opacity: 1, transform: 'scale(1)' })),
      ]),
    ]),
    trigger('countdown', [
      transition('* => *', [
        style({ transform: 'scale(1.2)' }),
        animate('100ms ease-out', style({ transform: 'scale(1)' })),
      ]),
    ]),
  ],
})
export class DebtDialogComponent implements OnInit, OnDestroy {
  @Input() amount = 0;
  @Input() set show(value: boolean) {
    this.visible = value;
    if (value) {
      this.startTimer();
    }
  }

  @Output() dialogClosed = new EventEmitter<void>();

  visible = false;
  timeLeft = signal(30);
  private timerSubscription: Subscription | undefined;
  private warningSound = new Audio('assets/sounds/warning.mp3');

  ngOnInit() {
    if (this.visible) {
      this.startTimer();
    }
  }

  ngOnDestroy() {
    this.stopTimer();
  }

  private startTimer() {
    this.timeLeft.set(30);
    this.timerSubscription = interval(1000)
      .pipe(takeWhile(() => this.timeLeft() > 0))
      .subscribe(() => {
        this.timeLeft.update((value) => value - 1);
        if (this.timeLeft() <= 5) {
          this.warningSound.play();
        }
        if (this.timeLeft() === 0) {
          setTimeout(() => this.closeDialog(), 5000);
        }
      });
  }

  private stopTimer() {
    if (this.timerSubscription) {
      this.timerSubscription.unsubscribe();
    }
  }

  closeDialog(): void {
    this.stopTimer();
    this.visible = false;
    this.dialogClosed.emit();
  }
}
