import { Component } from '@angular/core';
import { IonicModule, ModalController } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonDatetime } from '@ionic/angular';
import { DateTimePickerModal } from '../datetime-picker-modal/datetime-picker-modal.component';

@Component({
  selector: 'app-task-modal',
  templateUrl: './task-modal.component.html',
  styleUrls: ['./task-modal.component.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule, DateTimePickerModal]
})
export class TaskModalComponent {
  // 日期范围配置
  task = {
    title: '',
    tags: [] as string[],
    subtasks: [''] as string[],
    note: '',
    dueDate: new Date().toISOString().split('T')[0],
    dueTime: new Date(Date.now() + 3600000).toISOString().split('T')[1].substring(0,5)
  };

  newTag = '';

  constructor(private modalCtrl: ModalController) {}

  // 新增模态控制器实现
  addTag() {
    if (this.newTag) {
      this.task.tags.push(this.newTag.trim());
      this.newTag = '';
    }
  }

  removeTag(index: number) {
    this.task.tags.splice(index, 1);
  }

  addSubtask() {
    this.task.subtasks.push('');
  }

  removeSubtask(index: number) {
    this.task.subtasks.splice(index, 1);
  }

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

  confirm() {
    if (!this.task.title) {
      return;
    }
    this.modalCtrl.dismiss(this.task);
  }

  async openDateTimePicker() {
    const modal = await this.modalCtrl.create({
      component: DateTimePickerModal,
      componentProps: {
        initialDate: new Date(this.task.dueDate + 'T' + this.task.dueTime)
      }
    });

    modal.onDidDismiss().then(({ data }) => {
      if (data?.role === 'confirm') {
        const selectedDate = data.data as Date;
        this.task.dueDate = selectedDate.toISOString().split('T')[0];
        this.task.dueTime = selectedDate.toTimeString().substring(0,5);
      }
    });

    await modal.present();
  }
}
