import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { ModalController } from '@ionic/angular'; // 确保导入 ModalController
import { ArticleCardComponent } from '../component/article-card/article-card.component';
import { CommonModule } from '@angular/common';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { FormsModule } from '@angular/forms';
import {
  airplane,
  bluetooth,
  call,
  wifi,
  chevronDownCircle,
  chevronForwardCircle,
  chevronUpCircle,
  colorPalette,
  document,
  globe
} from 'ionicons/icons';
import { addIcons } from 'ionicons';
import { IonicModule } from '@ionic/angular'; // 导入 IonicModule

addIcons({
  airplane,
  bluetooth,
  call,
  wifi,
  chevronDownCircle,
  chevronForwardCircle,
  chevronUpCircle,
  colorPalette,
  document,
  globe
});

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: true,
  imports: [
    IonicModule, // 添加 IonicModule
    CommonModule,
    FormsModule,
    ArticleCardComponent,
    // 其他自定义组件或模块
  ]
})
export class Tab2Page implements OnInit, OnDestroy {
  selectedSegment: string = '热点';
  segments: string[] = ['热点', '专家科普', '睡眠', '生活', '男性', '女性', '两性', '辟谣', '母婴', '美容'];

  images: string[] = [
    'https://picsum.photos/800/400?random=7',
    'https://picsum.photos/800/400?random=8',
    'https://picsum.photos/800/400?random=9',
    'https://picsum.photos/800/400?random=10',
    'https://picsum.photos/800/400?random=11',
    'https://picsum.photos/800/400?random=12',
  ];

  currentSlide: number = 0;
  intervalId: any;

  products: CloudObject[] = [];
  allCards: CloudObject[] = [];
  cards: CloudObject[] = [];

  searchTerm: string = '';
  comment: string = '';
  shareLink: string = '';

  isModalOpen: boolean = false;
  currentProduct: CloudObject | null = null;

  shareDetail: boolean = false;

  isLoading: boolean = false;

  constructor(
    private modalCtrl: ModalController,
    private router: Router
  ) { }

  ngOnInit() {
    this.loadAllCards();
    this.loadCards();
    this.startAutoSlide();
  }

  ngOnDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

  // 轮播图功能
  nextSlide() {
    this.currentSlide = (this.currentSlide + 1) % this.images.length;
  }

  prevSlide() {
    this.currentSlide = (this.currentSlide - 1 + this.images.length) % this.images.length;
  }

  goToSlide(index: number) {
    this.currentSlide = index;
  }

  startAutoSlide() {
    this.intervalId = setInterval(() => this.nextSlide(), 3000);
  }

  // 搜索功能
  async searchProducts(event: any) {
    this.searchTerm = event.detail.value.toLowerCase();
    if (this.searchTerm) {
      this.products = this.allCards.filter(product =>
        product.get('topic').toLowerCase().includes(this.searchTerm) ||
        product.get('title').toLowerCase().includes(this.searchTerm) ||
        product.get('category').toLowerCase().includes(this.searchTerm) ||
        product.get('content')[0].toLowerCase().includes(this.searchTerm)
      );
    } else {
      this.products = [...this.allCards];
    }
  }

  // 分段控制
  segmentChanged(event: any) {
    this.selectedSegment = event.detail.value;
    this.loadCards();
  }

  // 加载所有卡片
  async loadAllCards() {
    this.isLoading = true;
    const query = new CloudQuery('HotDot');
    try {
      this.allCards = await query.find();
      this.products = [...this.allCards];
    } catch (error) {
      console.error('加载所有卡片失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  async loadCards() {
    this.isLoading = true;
    const query = new CloudQuery('HotDot');
    query.equalTo('category', this.selectedSegment);
    try {
      this.cards = await query.find();
    } catch (error) {
      console.error('加载分类卡片失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 打开详细信息模态
  openDetailModal(product: CloudObject) {
    const user = new CloudUser();
    if (!user.id) {
      this.router.navigate(['/tabs/tab4']);
      return;
    }
    this.isModalOpen = true;
    this.currentProduct = product;
  }

  closeDetailModal() {
    this.isModalOpen = false;
    this.currentProduct = null;
  }

  // 分享功能
  shareDetailModal() {
    this.shareDetail = true;
    this.shareLink = window.location.href; // 示例分享链接，可以根据需求调整
  }

  closeShareModal() {
    this.shareDetail = false;
  }

  copyLink() {
    navigator.clipboard.writeText(this.shareLink).then(() => {
      console.log('链接已复制');
      // 可以添加提示用户复制成功的反馈
    }).catch(err => {
      console.error('复制失败:', err);
    });
  }

  // 评论功能
  onCommentInput(event: any) {
    this.comment = event.detail.value;
  }

  postComment() {
    if (this.comment.trim()) {
      // 实现发布评论的逻辑，例如调用 API
      console.log('发布评论:', this.comment);
      this.comment = '';
    }
  }

  // 跟踪函数以优化 ngFor
  trackByIndex(index: number, item: any): number {
    return index;
  }

  trackById(index: number, item: CloudObject): string {
    return item.id ?? `no-id-${index}`; // 确保返回 string 类型，避免 null
  }

}