import { w2popup, w2utils } from "../vendor/w2ui";

type PopupActionEvent = {
  detail: {
    action: string;
    self?: {
      close?: () => void;
    };
  };
};

export function notify(message: string, title = "提示") {
  w2utils.alert({
    box: "body",
    title,
    text: message
  });
}

export function notifyError(error: unknown) {
  notify(error instanceof Error ? error.message : String(error), "错误");
}

export function confirmDialog(message: string, title = "确认") {
  return new Promise<boolean>((resolve) => {
    let settled = false;
    const settle = (value: boolean) => {
      if (settled) return;
      settled = true;
      resolve(value);
    };

    w2utils.confirm({
      box: "body",
      title,
      text: message,
      btn_yes: {
        text: "确定"
      },
      btn_no: {
        text: "取消"
      }
    })
      .yes(() => settle(true))
      .no(() => settle(false))
      .close(() => settle(false));
  });
}

export function formDialog<T>(options: {
  title: string;
  width?: number;
  height?: number;
  blockPage?: boolean;  
  body: string;
  onOpen?: () => void;
  onSubmit: () => Promise<T> | T;
}) {
  return new Promise<T | null>((resolve) => {
    let settled = false;
    const closeWith = (value: T | null) => {
      if (settled) return;
      settled = true;
      resolve(value);
      w2popup.close();
    };

    const popup = w2popup.open({
      title: options.title,
      width: options.width ?? 460,
      height: options.height ?? 300,
      modal: true,
      body: options.body,
      blockPage: options.blockPage ?? false,  
      actions: {
        取消() {
          closeWith(null);
        },
        async 确定() {
          try {
            const result = await options.onSubmit();
            closeWith(result);
          } catch (error) {
            notifyError(error);
          }
        }
      }
    });

    popup.self
      .on("open:after", () => options.onOpen?.())
      .on("close:after", () => {
        if (!settled) resolve(null);
      })
      .on("action:after", (event: unknown) => {
        const popupEvent = event as PopupActionEvent;
        if (popupEvent.detail.action === "close") {
          closeWith(null);
        }
      });
  });
}

export async function promptDialog(options: {
  title: string;
  label: string;
  value?: string;
  placeholder?: string;
}) {
  const id = `field-${Date.now()}`;
  return formDialog<string>({
    title: options.title,
    height: 210,
    blockPage: false,
    body: `
      <div class="popup-form">
        <label>
          <span>${options.label}</span>
          <input id="${id}" value="${options.value ?? ""}" placeholder="${options.placeholder ?? ""}" />
        </label>
      </div>
    `,
    onOpen: () => document.querySelector<HTMLInputElement>(`#${id}`)?.focus(),
    onSubmit: () => {
      const value = document.querySelector<HTMLInputElement>(`#${id}`)?.value.trim() ?? "";
      if (!value) {
        throw new Error(`${options.label}不能为空`);
      }
      return value;
    }
  });
}
