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

interface Memo {
  memoId: number;
  username: string;
  content: string;
  timestamp: Date;
}

@Component({
  selector: 'app-memo',
  templateUrl: './memo.page.html',
  styleUrls: ['./memo.page.scss'],
})
export class MemoPage implements OnInit {
  segment: string = 'memo';
  memos: Memo[] = [];
  newMemo: string = '';
  username: string = ''; // Current user's username
  nextMemoId: number = 1; // Track next memoId for the current user

  constructor(private alertController: AlertController, private router: Router) {}

  ngOnInit() {
    const currentUser = Parse.User.current();
    if (currentUser) {
      this.username = currentUser.getUsername()!;
      this.loadMemos();
      this.loadNextMemoId(); // Load the next memoId for the current user
    } else {
      console.error('User not logged in.');
    }
  }

  async loadNextMemoId() {
    try {
      const query = new Parse.Query('memo_history');
      query.equalTo('username', this.username);
      query.descending('memoId');
      query.limit(1); // Limit to the last memo to get the highest memoId
      const result = await query.first();

      if (result) {
        this.nextMemoId = result.get('memoId') + 1;
      } else {
        this.nextMemoId = 1; // Initialize to 1 if no memos exist for the user
      }
    } catch (error) {
      console.error('Error loading next memoId', error);
    }
  }

  async loadMemos() {
    try {
      const query = new Parse.Query('memo_history');
      query.equalTo('username', this.username);
      query.descending('createdAt');
      query.limit(3); // Limit to latest three memos
      const results = await query.find();

      this.memos = results.map((memo: any) => ({
        memoId: memo.get('memoId'),
        username: memo.get('username'),
        content: memo.get('content'),
        timestamp: memo.get('time'),
      }));

    } catch (error) {
      console.error('Error loading memos', error);
    }
  }

  async addMemo() {
    if (this.newMemo.trim().length > 0) {
      const MemoClass = Parse.Object.extend('memo_history');
      const memo = new MemoClass();

      memo.set('username', this.username);
      memo.set('memoId', this.nextMemoId); // Assign the next available memoId
      memo.set('content', this.newMemo);
      memo.set('time', new Date());

      try {
        await memo.save();
        this.loadMemos(); // Reload memos after adding a new one
        this.newMemo = '';
        this.nextMemoId++; // Increment the next memoId for future memos

        const alert = await this.alertController.create({
          header: '提示',
          message: '添加成功',
          buttons: ['确定']
        });
        await alert.present();

      } catch (error) {
        console.error('Error saving memo', error);
      }
    }
  }

  async confirmDeleteMemo(memo: Memo) {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: `你确定要删除 "${memo.content}" 吗？`,
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '删除',
          handler: () => {
            this.deleteMemo(memo);
          }
        }
      ]
    });
    await alert.present();
  }

  async deleteMemo(memo: Memo) {
    const MemoClass = Parse.Object.extend('memo_history');
    const query = new Parse.Query(MemoClass);
    query.equalTo('memoId', memo.memoId);
    
    try {
      const result = await query.first();
      if (result) {
        await result.destroy();
        this.loadMemos(); // Reload memos after deleting one
      }
    } catch (error) {
      console.error('Error deleting memo', error);
    }
  }

  // Navigate to memo-history page
  navigateToMemoHistory() {
    this.router.navigate(['/tabs/memo-history']);
  }
}
