import { ComponentContent } from '@kit.ArkUI';
import { StrUtil } from '@pura/harmony-utils';
import { DialogCallback } from '../callback/DialogCallback';
import { ToastUtils } from '../utils/ToastUtils';

export declare class DatePickerDialogOption {
  selectedDate: Date;
  confirm?: (date: Date) => void;
}

@Builder
function defaultBuilder(option: DatePickerDialogOption) {
  Column() {
    Row() {
      Text('取消').fontColor($r('app.color.color_999999')).fontSize(14)
        .onClick(() => {
          DatePickerDialog.dismiss()
        })
      Blank().layoutWeight(1)
      Text('确定').fontColor($r('app.color.color_466afd')).fontSize(14)
        .onClick(() => {
          if (option.confirm) {
            option.confirm(option.selectedDate)
          }
          DatePickerDialog.dismiss()
        })
    }.padding({ left: 16, right: 16 })

    DatePicker({
      start: new Date('1970-1-1'),
      end: new Date('2100-1-1'),
      selected: option.selectedDate
    })
      .onDateChange((value: Date) => {
        option.selectedDate = value
      })
      .margin({ top: 20, bottom: 30 })
  }
  .padding({ top: 22, bottom: 22 })
  .borderRadius(20)
  .backgroundColor($r('app.color.window_background'))
  .width('100%')
}

export class DatePickerDialog {
  context: UIContext | null = null;
  contentNode: ComponentContent<Object> | null = null;
  private static instance: DatePickerDialog | null = null;

  static show(context: UIContext, option: DatePickerDialogOption) {
    if (DatePickerDialog.instance === null) {
      DatePickerDialog.instance = new DatePickerDialog(context, option);
    }
    DatePickerDialog.instance?.openDialog();
  }

  static dismiss() {
    if (DatePickerDialog.instance !== null) {
      DatePickerDialog.instance.closeDialog();
      DatePickerDialog.instance = null;
    }
  }

  constructor(context: UIContext, option: DatePickerDialogOption) {
    this.context = context;
    this.contentNode = new ComponentContent(context, wrapBuilder(defaultBuilder), option);
  }

  openDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().openCustomDialog(this.contentNode, {
        maskColor: '#CC000000',
        autoCancel: false,
        alignment: DialogAlignment.Bottom
      })
        .then(() => {
          console.info('OpenCustomDialog complete.');
        })
    }
  }

  closeDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().closeCustomDialog(this.contentNode)
        .then(() => {
          console.info('CloseCustomDialog complete.');
        })
    }
  }
}