import { Component, OnInit,OnDestroy } from '@angular/core';
import { AlertController, NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import * as Parse from 'parse';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit,OnDestroy {
  initial: string = '0KG';
  current: string = '0KG';
  target: string = '0KG';
  reward: string = '0元';
  username: string = ''; // 当前用户的用户名
  blueColor: boolean = false;
  private loadUserDataSubscription: Subscription | undefined;
  
  constructor(
    private alertController: AlertController,
    private router: Router,
    private navCtrl: NavController,
    
  ) {}

  ngOnInit() {
    this.loadUserData();
    //每隔一秒检测登录状况
    this.loadUserDataSubscription = interval(1000).subscribe(() => {
      this.loadUserData();
      console.log(this.username);
    });
  }

  ngOnDestroy() {
    if (this.loadUserDataSubscription) {
      this.loadUserDataSubscription.unsubscribe();
    }
  }

  async loadUserData() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      this.username = currentUser.getUsername()!;
      this.loadData();
    } else {
      this.username = '未登录';
      this.loadData();
    }
  }

  async loadData() {
    try {
      const query = new Parse.Query('weight_status');
      query.equalTo('username', this.username); // 查找当前用户的数据
      const weightStatus = await query.first();
      if (weightStatus) {
        this.initial = weightStatus.get('initial') + 'KG' || '--KG';
        this.current = weightStatus.get('current') + 'KG' || '--KG';
        this.target = weightStatus.get('target') + 'KG' || '--KG';
        this.reward = weightStatus.get('reward') + '元' || '--元';
      }
    } catch (error) {
      console.error('Error loading data', error);
    }
  }

  async openEditModal() {
    if (this.username == '未登录') {
      // 如果用户未登录，则显示登录提示
      this.presentLoginAlert();
      return;
    }

    const alert = await this.alertController.create({
      header: '编辑体重信息',
      inputs: [
        {
          name: 'initial',
          type: 'text',
          placeholder: '初始',
          value: this.initial.replace('KG', '')
        },
        {
          name: 'current',
          type: 'text',
          placeholder: '当前',
          value: this.current.replace('KG', '')
        },
        {
          name: 'target',
          type: 'text',
          placeholder: '目标',
          value: this.target.replace('KG', '')
        },
        {
          name: 'reward',
          type: 'text',
          placeholder: '赏金',
          value: this.reward.replace('元', '')
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '保存',
          handler: async (data) => {
            try {
              const query = new Parse.Query('weight_status');
              query.equalTo('username', this.username); // 查找当前用户的数据
              let weightStatus = await query.first();
              if (!weightStatus) {
                weightStatus = new Parse.Object('weight_status');
              }
              weightStatus.set('username', this.username);
              weightStatus.set('initial', data.initial);
              weightStatus.set('current', data.current);
              weightStatus.set('target', data.target);
              weightStatus.set('reward', data.reward);
              await weightStatus.save();
              this.loadData(); // 更新本地数据
            } catch (error) {
              console.error('Error updating data', error);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  async presentLoginAlert() {
    const alert = await this.alertController.create({
      header: '未登录',
      message: '请先登录以继续操作',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '去登录',
          handler: () => {
            this.navCtrl.navigateForward('/user/login');
          }
        }
      ]
    });

    await alert.present();
  }

  toggleButtonColor(habit: string) {
    this.blueColor = !this.blueColor;
  }


  //每日习惯按钮颜色变化
  buttons = [
    { text: '足量饮水', color: 'light', icon: 'water' },
    { text: '干净饮食', color: 'light', icon: 'nutrition' },
    { text: '健康作息', color: 'light', icon: 'bed' },
    { text: '有氧', color: 'light', icon: 'bicycle' },
    { text: '力量', color: 'light', icon: 'barbell' },
    { text: '拉伸', color: 'light', icon: 'body' }
  ];

  habitText = '今日习惯待保持';

  onButtonClick(index: number) {
    const button = this.buttons[index];
    switch(button.color) {
      case 'light':
        button.color = 'success';
        break;
      case 'success':
        button.color = 'danger';
        break;
      case 'danger':
        button.color = 'light';
        break;
    }
  
    this.checkHabitText();
  }
  
  checkHabitText() {
    if (this.buttons.every(btn => btn.color === 'success')) {
      this.habitText = '你成功保持了良好的习惯';
    } else if (this.buttons.some(btn => btn.color === 'danger')) {
      this.habitText = '今日好习惯保持失败，再接再厉';
    } else {
      this.habitText = '今日习惯待保持';
    }
  }
  
  get allButtonsSuccess() {
    return this.buttons.every(btn => btn.color === 'success');
  }
  
  get anyButtonFailure() {
    return this.buttons.some(btn => btn.color === 'danger');
  }


  navigateToTreePage() {
    this.router.navigate(['/tabs/tree']);
  }
}
