import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  OnDestroy,
} from '@angular/core';
import {
  IonButton,
  IonContent,
  IonIcon,
  IonCard,
  IonCardContent,
  IonLabel,
  IonItem,
  IonSpinner,
} from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { Subject, takeUntil } from 'rxjs';

@Component({
  selector: 'app-edittag',
  templateUrl: './edittag.component.html',
  styleUrls: ['./edittag.component.scss'],
  standalone: true,
  imports: [
    IonCardContent,
    IonCard,
    IonIcon,
    IonContent,
    IonButton,
    IonLabel,
    IonItem,
    CommonModule,
    IonSpinner,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush, // 使用按需变更检测
})
export class EdittagComponent implements OnInit {
  @Input() iconName: string = '';
  @Input() label: string = '';
  @Input() route: string = ''; // The route to navigate to on click
  @Input() disabled: boolean = false; // 是否禁用按钮
  @Input() loading: boolean = false; // 加载状态
  @Output() clicked = new EventEmitter<void>(); // 点击事件

  private click$ = new Subject<void>();
  private destroy$ = new Subject<void>();

  constructor(private router: Router, private cd: ChangeDetectorRef) {}

  ngOnInit(): void {
    this.click$.pipe(takeUntil(this.destroy$)).subscribe(() => {
      if (!this.disabled && !this.loading) {
        this.clicked.emit(); // 触发点击事件
        this.navigate();
      }
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  onClick(): void {
    if (!this.disabled && !this.loading) {
      this.loading = true;
      this.cd.markForCheck(); // 手动触发变更检测
      this.click$.next();
      setTimeout(() => {
        this.loading = false;
        this.cd.markForCheck(); // 手动触发变更检测
      }, 300); // 模拟加载时间
    }
  }

  private navigate(): void {
    if (this.route) {
      this.router.navigate([this.route]);
    }
  }
}
