import { Component, Input, Output, EventEmitter } from '@angular/core';
import { IonDatetime, ModalController } from '@ionic/angular';
import { ViewChild } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';

@Component({
  standalone: true,
  imports: [
    IonicModule,
    CommonModule
  ],
  selector: 'app-datetime-picker-modal',
  template: `
    <ion-header>
      <ion-toolbar color="light">
        <ion-buttons slot="start">
          <ion-button (click)="dismiss()">取消</ion-button>
        </ion-buttons>
        <ion-title>选择时间</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="confirm()" [strong]="true">确定</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <ion-datetime
        [value]="initialDate"
        [min]="minDate"
        [max]="maxDate"
        presentation="date-time"
      ></ion-datetime>
    </ion-content>
  `,
  styles: [
    `ion-datetime {
      --background: white;
      margin: 16px;
      border-radius: 16px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    }`
  ]
})
export class DateTimePickerModal {
  @Input() initialDate!: string | Date;
  @Input() minDate?: string;
  @Input() maxDate?: string;

@Output() confirmed = new EventEmitter<Date>();

  constructor(private modalCtrl: ModalController) {}

// 导入 ViewChild
@ViewChild(IonDatetime) datetime!: IonDatetime;

  confirm() {
    if (!this.datetime.value) return;
    const selectedDate = new Date(this.datetime.value as string | Date);
    this.confirmed.emit(selectedDate);
    this.modalCtrl.dismiss({
      data: selectedDate,
      role: 'confirm'
    });
  }

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