import { App } from "antd";
import { useCallback } from "react";

export interface ConfirmOptions {
  title: string;
  content?: string;
  okText?: string;
  cancelText?: string;
  onOk?: () => Promise<void> | void;
  onCancel?: () => void;
  type?: "confirm" | "info" | "success" | "error" | "warning";
}

export const useModal = () => {
  const { modal, message } = App.useApp();

  // 通用确认对话框
  const showConfirm = useCallback(
    (options: ConfirmOptions) => {
      const {
        title,
        content,
        okText = "确定",
        cancelText = "取消",
        onOk,
        onCancel,
        type = "confirm",
      } = options;

      const modalMethod = modal[type];

      return modalMethod({
        title,
        content,
        okText,
        cancelText,
        onOk,
        onCancel,
      });
    },
    [modal]
  );

  // 删除确认对话框
  const showDeleteConfirm = useCallback(
    (
      onConfirm: () => Promise<void> | void,
      title: string = "删除确认",
      content: string = "确定要删除吗？此操作不可恢复。"
    ) => {
      return modal.confirm({
        title,
        content,
        okText: "删除",
        cancelText: "取消",
        okType: "danger",
        onOk: async () => {
          try {
            await onConfirm();
            message.success("删除成功");
          } catch (error) {
            message.error("删除失败");
            throw error;
          }
        },
      });
    },
    [modal, message]
  );

  // 编辑确认对话框
  const showEditConfirm = useCallback(
    (
      onConfirm: () => Promise<void> | void,
      title: string = "编辑确认",
      content: string = "确定要保存修改吗？"
    ) => {
      return modal.confirm({
        title,
        content,
        okText: "保存",
        cancelText: "取消",
        onOk: async () => {
          try {
            await onConfirm();
            message.success("保存成功");
          } catch (error) {
            message.error("保存失败");
            throw error;
          }
        },
      });
    },
    [modal, message]
  );

  // 状态切换确认对话框
  const showStatusConfirm = useCallback(
    (
      onConfirm: () => Promise<void> | void,
      action: string,
      itemName: string = "该项"
    ) => {
      return modal.confirm({
        title: `${action}确认`,
        content: `确定要${action}${itemName}吗？`,
        okText: action,
        cancelText: "取消",
        onOk: async () => {
          try {
            await onConfirm();
            message.success(`${action}成功`);
          } catch (error) {
            message.error(`${action}失败`);
            throw error;
          }
        },
      });
    },
    [modal, message]
  );

  return {
    modal,
    message,
    showConfirm,
    showDeleteConfirm,
    showEditConfirm,
    showStatusConfirm,
  };
};
