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

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

  ngOnInit() {}

  ionViewDidEnter() {
    this.loadUserData();
  }

  ngOnDestroy() {}

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

  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') || 0;
        this.current = weightStatus.get('current') || 0;
        this.target = weightStatus.get('target') || 0;
        this.reward = this.calculateReward(this.initial, this.target);
      }
    } catch (error) {
      console.error('Error loading data', error);
    }
  }

  calculateReward(initial: number, target: number): number {
    return (initial - target) * 10;
  }

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

    const alert = await this.alertController.create({
      header: '编辑体重信息',
      subHeader: '请根据您的需求编辑以下信息',
      inputs: [
        {
          name: 'initial',
          type: 'number',
          placeholder: '初始',
          value: this.initial.toString()
        },
        {
          name: 'current',
          type: 'number',
          placeholder: '当前',
          value: this.current.toString()
        },
        {
          name: 'target',
          type: 'number',
          placeholder: '目标',
          value: this.target.toString()
        },
        {
          name: 'reward',
          type: 'number',
          placeholder: '赏金',
          value: this.reward.toString(),
          disabled: true // 禁用输入框，显示但不能编辑
        }
      ],
      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');
              }
              const rewardValue = this.calculateReward(Number(data.initial), Number(data.target));
              weightStatus.set('username', this.username);
              weightStatus.set('initial', Number(data.initial));
              weightStatus.set('current', Number(data.current));
              weightStatus.set('target', Number(data.target));
              weightStatus.set('reward', rewardValue);
              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/timer']);
  }
}
