import { Component, OnInit, Renderer2, ElementRef, Input } from '@angular/core';
import { ModalController, AnimationController, NavController } from '@ionic/angular';
import { IonicModule } from '@ionic/angular';
import { Router } from '@angular/router'; // 新增Router导入

// 独立的紧急模态组件
@Component({
  selector: 'app-emergency-modal',
  template: `
    <ion-header>
      <ion-toolbar color="danger">
        <ion-title>紧急通知</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="dismiss()">关闭</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <p>{{ alert?.message }}</p>
      <ion-button expand="block" (click)="dismiss()">我知道了</ion-button>
    </ion-content>
  `,
  styles: [`
    ion-content {
      --background: #fff1f0;
    }
  `],
  imports: [IonicModule],
  standalone: true
})
export class EmergencyModal {
  @Input() alert: any;

  constructor(private modalCtrl: ModalController) {}

  dismiss() {
    this.modalCtrl.dismiss();
  }
}

// 独立的语音输入模态组件
@Component({
  selector: 'app-voice-input-modal',
  template: `
    <ion-header>
      <ion-toolbar>
        <ion-title>语音输入</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="dismiss()">关闭</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <div class="voice-input-container">
        <ion-button shape="round" color="primary" size="large">
          <ion-icon name="mic" slot="start"></ion-icon>
          按住说话
        </ion-button>
        <p class="hint">请说出您的需求，例如："需要帮忙买药"</p>
      </div>
    </ion-content>
  `,
  styles: [`
    .voice-input-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 60vh;
    }
    .hint {
      margin-top: 20px;
      color: var(--ion-color-medium);
      text-align: center;
    }
  `],
  imports: [IonicModule],
  standalone: true
})
export class VoiceInputModal {
  constructor(private modalCtrl: ModalController) {}

  dismiss() {
    this.modalCtrl.dismiss();
  }
}

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: false,
})
export class Tab1Page implements OnInit {
  // 用户数据
  currentUser: any = { name: '王阿姨', role: 'elderly' };
  isElderly: boolean = true;

  // 动态问候语
  greetingMessage: string = '';

  // 紧急状态
  emergencyAlert: any = null;

  // 服务九宫格
  services = [
    { id: 'emergency', name: '紧急求助', icon: 'warning', badge: 1, priority: 5 },
    { id: 'medicine', name: '代买药品', icon: 'medical', badge: 0, priority: 3 },
    { id: 'tools', name: '工具借用', icon: 'construct', badge: 2, priority: 2 },
    { id: 'chat', name: '老人陪聊', icon: 'chatbubbles', badge: 0, priority: 4 },
    { id: 'ai', name: 'AI管家', icon: 'headset', badge: 0, priority: 1 },
    { id: 'shop', name: '积分商城', icon: 'gift', badge: 0, priority: 1 },
    { id: 'events', name: '社区活动', icon: 'calendar', badge: 0, priority: 3 },
    { id: 'skills', name: '技能交换', icon: 'people', badge: 0, priority: 2 },
    { id: 'my', name: '我的服务', icon: 'list', badge: 0, priority: 1 }
  ];

  // 互助信息流
  communityFeed = [
    {
      userName: '张阿姨',
      userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
      description: '需要帮忙修理水龙头',
      type: 'normal',
      time: new Date(),
      points: 10,
      status: 'pending'
    },
    {
      userName: '李大爷',
      userAvatar: 'https://ionicframework.com/docs/img/demos/avatar.svg',
      description: '求购降压药',
      type: 'emergency',
      time: new Date(Date.now() - 3600000),
      points: 20,
      status: 'completed'
    }
  ];

  // 子女消息
  childrenMessages = [
    {
      from: '儿子',
      text: '妈，我给您约了周四体检',
      time: new Date(),
      played: false
    }
  ];

  // 是否夜间模式
  isNightMode: boolean = false;

  constructor(
    private modalCtrl: ModalController,
    private renderer: Renderer2,
    private el: ElementRef,
    private animationCtrl: AnimationController,
    private navCtrl: NavController,
    private router: Router // 新增Router依赖注入
  ) {}

  ngOnInit() {
    this.setGreeting();
    this.checkNightMode();
    this.animateAssistant();

    // 模拟紧急警报
    setTimeout(() => {
      this.emergencyAlert = { 
        message: '暴雨红色预警！点击查看避灾物资点',
        level: 'danger'
      };
      this.pulseEmergencyBar();
    }, 3000);
  }

  // 设置动态问候语
  setGreeting() {
    const now = new Date();
    const hour = now.getHours();
    let timeGreeting = '';

    if (hour < 5) timeGreeting = '夜深了';
    else if (hour < 11) timeGreeting = '早安';
    else if (hour < 14) timeGreeting = '午安';
    else if (hour < 18) timeGreeting = '下午好';
    else timeGreeting = '晚上好';

    this.greetingMessage = `${timeGreeting}，${this.currentUser.name}！今日社区有剪纸活动（步行3分钟）`;
  }

  // 检查是否夜间模式
  checkNightMode() {
    const now = new Date();
    const hour = now.getHours();
    this.isNightMode = hour >= 22 || hour < 6;
  }

  // 紧急状态条动画
  async pulseEmergencyBar() {
    const emergencyBar = this.el.nativeElement.querySelector('.emergency-bar');
    if (emergencyBar) {
      const animation = this.animationCtrl.create()
        .addElement(emergencyBar)
        .duration(1000)
        .iterations(Infinity)
        .keyframes([
          { offset: 0, opacity: '0.7', transform: 'scale(1)' },
          { offset: 0.5, opacity: '1', transform: 'scale(1.02)' },
          { offset: 1, opacity: '0.7', transform: 'scale(1)' }
        ]);
      await animation.play();
    }
  }

  // 悬浮助手动画
  async animateAssistant() {
    const assistant = this.el.nativeElement.querySelector('.assistant-button');
    if (assistant) {
      // 呼吸动画
      const breathAnimation = this.animationCtrl.create()
        .addElement(assistant)
        .duration(3000)
        .iterations(Infinity)
        .fromTo('transform', 'translateY(0)', 'translateY(-5px)')
        .fromTo('opacity', '0.9', '1');

      await breathAnimation.play();
    }
  }

  // 打开紧急模态框
  async openEmergencyModal() {
    const modal = await this.modalCtrl.create({
      component: EmergencyModal,
      componentProps: {
        alert: this.emergencyAlert
      },
      cssClass: 'emergency-modal'
    });
    return await modal.present();
  }

  // 打开语音输入模态框
  async openVoiceInput() {
    const modal = await this.modalCtrl.create({
      component: VoiceInputModal,
      cssClass: 'voice-input-modal'
    });
    return await modal.present();
  }

  // 播放子女语音消息
  playMessage(message: any) {
    message.played = true;
    console.log('播放消息:', message.text);
  }

  // 积分绽放动画
  async playPointsAnimation(event: any) {
    const card = event.target.closest('ion-item');
    if (card) {
      const animation = this.animationCtrl.create()
        .addElement(card)
        .duration(1000)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '1' },
          { offset: 0.5, transform: 'scale(1.05)', opacity: '0.8' },
          { offset: 1, transform: 'scale(1)', opacity: '1' }
        ]);
      await animation.play();
    }
  }

  goDynamic(dynamic?: string) {
    this.navCtrl.navigateForward(["tab1", "dynamic"]);
  }

  // 处理服务项点击
  handleServiceClick(serviceId: string) {
    switch (serviceId) {
      case 'ai':
        this.navigateToAiAgent(); // AI管家导航
        break;
      case 'emergency':
        this.openEmergencyModal(); // 紧急求助模态框
        break;
      // 其他服务可补充对应逻辑
    }
  }

  // 跳转到AI管家页面方法
  navigateToAiAgent() {
    this.router.navigate(['/ai-agent']); // 使用Router进行导航
  }
} // 此处为 Tab1Page 类的正确闭合

// 原错误代码块已删除（错误的 @Component 装饰器及内部方法）

