import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnDestroy,
} from '@angular/core';


@Component({
  selector: 'ccl-toast',
  standalone: true,
  imports: [],
  templateUrl: './toast.html',
  styleUrls: ['./toast.css'],
})
export class ToastComponent implements OnInit, OnDestroy {
  @Input() variant: 'info' | 'success' | 'warning' | 'error' = 'info';
  @Input() message = '';
  @Input() title?: string;
  @Input() duration = 3000; // ms
  @Input() dismissible = true;
  @Input() position: 'top-right' | 'top-left' | 'top-center' | 'bottom-right' | 'bottom-left' | 'bottom-center' =
    'bottom-right';
  @Input() animation: 'slide' | 'fade' | 'none' = 'slide';
  @Input() showProgress = true;
  @Input() pauseOnHover = true;
  @Input() ariaLive: 'polite' | 'assertive' | 'off' = 'polite';
  @Input() role: 'alert' | 'status' | 'log' = 'status';

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

  private timer?: ReturnType<typeof setTimeout>;
  private progressTimer?: ReturnType<typeof setInterval>;
  progress = 100;
  isVisible = false;
  isExiting = false;

  ngOnInit() {
    // Trigger animation
    setTimeout(() => this.isVisible = true, 10);
    
    if (this.duration > 0) {
      this.timer = setTimeout(() => this.close(), this.duration);
      
      // Progress bar animation
      if (this.showProgress) {
        const interval = 50; // Update every 50ms
        const decrement = (interval / this.duration) * 100;
        this.progressTimer = setInterval(() => {
          this.progress -= decrement;
          if (this.progress <= 0) {
            this.progress = 0;
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
          }
        }, interval);
      }
    }
  }

  ngOnDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
    }
  }

  close() {
    this.isExiting = true;
    this.isVisible = false;
    // Wait for animation to complete before emitting closed event
    setTimeout(() => {
      this.closed.emit();
    }, 300);
  }

  onMouseEnter() {
    if (this.pauseOnHover && this.timer) {
      clearTimeout(this.timer);
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
      }
    }
  }

  onMouseLeave() {
    if (this.pauseOnHover && this.duration > 0) {
      const remainingTime = (this.progress / 100) * this.duration;
      this.timer = setTimeout(() => this.close(), remainingTime);
      
      if (this.showProgress) {
        const interval = 50;
        const decrement = (interval / remainingTime) * 100;
        this.progressTimer = setInterval(() => {
          this.progress -= decrement;
          if (this.progress <= 0) {
            this.progress = 0;
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
          }
        }, interval);
      }
    }
  }

  getDefaultIcon(): string {
    switch (this.variant) {
      case 'success': return '✓';
      case 'warning': return '⚠';
      case 'error': return '✕';
      case 'info':
      default: return 'ℹ';
    }
  }

  private _toastId: string = `toast-${Math.random().toString(36).substring(2, 9)}`;
  
  get toastId(): string {
    return this._toastId;
  }

  get ariaAttributes(): { [key: string]: any } {
    const attrs: { [key: string]: any } = {
      'role': this.role,
      'aria-live': this.ariaLive
    };
    
    if (this.title) {
      attrs['aria-labelledby'] = `${this.toastId}-title`;
    }
    
    return attrs;
  }

  get shouldAnnounce(): boolean {
    return this.ariaLive !== 'off' && this.message.length > 0;
  }
}
