import { Component, CUSTOM_ELEMENTS_SCHEMA, ViewChild } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonSearchbar, IonIcon, IonTabs, IonLabel, IonTabButton, IonTabBar, IonCard, IonCardHeader, IonCardContent, IonCardTitle, IonCardSubtitle, IonButton, IonTextarea, AlertController } from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
import { EditTagComponent } from '../edit-tag/edit-tag.component'
import { EditRatingStarComponent } from '../edit-rating-star/edit-rating-star.component';
import { CompMarkmapComponent } from '../comp-markmap/comp-markmap.component';
import { CloudQuery } from 'src/lib/ncloud';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  imports: [
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    ExploreContainerComponent,
    EditTagComponent,
    EditRatingStarComponent,
    IonSearchbar,
    IonIcon,
    IonTabs,
    IonLabel,
    IonTabButton,
    IonTabBar,
    CompMarkmapComponent,
    IonCardSubtitle,
    IonCard,
    IonCardHeader,
    IonCardContent,
    IonCardTitle,
    IonButton,
    IonTextarea,
    FormsModule
  ]
})
export class Tab2Page {

  async loadMapList() {
    let query = new CloudQuery("GoPlan");
    this.mapListOnline = await query.find();
    if (this.mapListOnline.length > 0) {
      this.currentIndex = 0;
      this.refreshMarkmap();
    }
  }
  mapListOnline: any = []
  mapList = [
    {
      title: "demo", content: ` ---
markmap:
  maxWidth: 300
  colorFreezeLevel: 2
---

# markmap

## Links

- <https://markmap.js.org/>
- [GitHub](https://github.com/markmap/markmap)

## Related

- [coc-markmap](https://github.com/markmap/coc-markmap)
- [gatsby-remark-markmap](https://github.com/markmap/gatsby-remark-markmap)

## Features

- links
- **inline** ~~text~~ *styles*
- multiline
  text
- inline code
- Katex - $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$
- This is a very very very very very very very very very very very very very very very long line.`},
    {
      title: "每日学习计划", content: `# 每日学习计划
## 时间
## 计划
## 总结      
      `},
    {
      title: "每周学习计划", content: `# 每周学习计划
## 时间
## 计划
## 总结        
        `}
  ]
  constructor(
    private alertController: AlertController
  ) {
    this.loadMapList();
  }

  currentScore: number = 0; // 初始分值

  handleScoreChange(newScore: number) {
    this.currentScore = newScore;
    console.log('新分值:', newScore); // 处理分值变化
  }

  currentIndex: number = 0;

  nextPlan() {
    if (this.currentIndex < this.mapListOnline.length - 1) {
      this.currentIndex++;
      this.refreshMarkmap();
    }
  }

  previousPlan() {
    if (this.currentIndex > 0) {
      this.currentIndex--;
      this.refreshMarkmap();
    }
  }

  @ViewChild(CompMarkmapComponent) markmapComponent?: CompMarkmapComponent;

  currentTitle: string = '';

  onTitleExtracted(title: string) {
    this.currentTitle = title;
  }

  refreshMarkmap() {
    setTimeout(() => {
      if (this.markmapComponent) {
        const markdown = this.mapListOnline[this.currentIndex].get('markmap');
        this.nodeStates = this.mapListOnline[this.currentIndex].get('nodeStates') || {};

        this.markmapComponent.markdown = markdown;
        this.markmapComponent.loadMarkMap();
        this.currentTitle = this.markmapComponent.extractTitle(markdown);
      }
    }, 100);
  }

  isEditing = false;
  editingMarkdown = '';

  editPlan() {
    this.isEditing = true;
    this.editingMarkdown = this.mapListOnline[this.currentIndex].get('markmap');
  }

  cancelEdit() {
    this.isEditing = false;
    this.editingMarkdown = '';
  }

  async savePlan() {
    try {
      const currentPlan = this.mapListOnline[this.currentIndex];
      await currentPlan.set('markmap', this.editingMarkdown);
      await currentPlan.save();

      this.isEditing = false;
      this.refreshMarkmap();

      // 显示成功提示
      const toast = document.createElement('ion-toast');
      toast.message = '计划已保存';
      toast.duration = 2000;
      toast.position = 'bottom';
      document.body.appendChild(toast);
      await toast.present();
    } catch (error) {
      console.error('Error saving plan:', error);
      // 显示错误提示
      const toast = document.createElement('ion-toast');
      toast.message = '保存失败，请重试';
      toast.duration = 2000;
      toast.position = 'bottom';
      toast.color = 'danger';
      document.body.appendChild(toast);
      await toast.present();
    }
  }

  async confirmDelete() {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: '是否删除该计划？删除后将无法恢复。',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary'
        },
        {
          text: '删除',
          role: 'destructive',
          handler: () => {
            this.deletePlan();
          }
        }
      ]
    });

    await alert.present();
  }

  async deletePlan() {
    try {
      const currentPlan = this.mapListOnline[this.currentIndex];
      if (!currentPlan) return;

      // 删除计划
      await currentPlan['destroy']();

      // 重新加载计划列表
      await this.loadMapList();

      // 显示成功提示
      const toast = document.createElement('ion-toast');
      toast.message = '计划已删除';
      toast.duration = 2000;
      toast.position = 'bottom';
      document.body.appendChild(toast);
      await toast.present();

    } catch (error) {
      console.error('Error deleting plan:', error);
      // 显示错误提示
      const toast = document.createElement('ion-toast');
      toast.message = '删除失败，请重试';
      toast.duration = 2000;
      toast.position = 'bottom';
      toast.color = 'danger';
      document.body.appendChild(toast);
      await toast.present();
    }
  }

  // 存储节点状态
  nodeStates: { [key: string]: boolean } = {};

  // 处理节点状态变化
  async onNodeStateChange(event: { nodeId: string, checked: boolean }) {
    this.nodeStates[event.nodeId] = event.checked;

    // 保存状态到数据库
    try {
      const currentPlan = this.mapListOnline[this.currentIndex];
      await currentPlan.set('nodeStates', this.nodeStates);
      await currentPlan.save();
    } catch (error) {
      console.error('Error saving node states:', error);
    }
  }
}
