import 'package:flutter/material.dart';
import 'package:get/get.dart';

class VAlertDialog extends StatelessWidget {
  /// 标题
  final String? title;

  /// 内容
  final Widget content;

  /// 内容内距
  final EdgeInsetsGeometry? contentPadding;

  /// 宽度
  final double width;

  /// 确定按钮文本
  final String confirmLabel;

  /// 取消按钮文本
  final String cancelLabel;

  /// 取消回调
  final VoidCallback? onCanceled;

  /// 确定回调，不为空则显示确定按钮
  final VoidCallback? onConfirm;

  /// 是否显示取消按钮
  final bool showCancel;

  const VAlertDialog({
    super.key,
    this.title,
    required this.content,
    this.contentPadding,
    this.width = 460,
    this.confirmLabel = "确定",
    this.cancelLabel = "取消",
    this.onCanceled,
    this.onConfirm,
    this.showCancel = true,
  });

  static Future<T?> showDialog<T>(Widget child) async {
    return await Get.dialog<T>(
      child,
      barrierDismissible: false,
      barrierColor: Colors.black.withOpacity(.1),
    );
  }

  @override
  Widget build(BuildContext context) {
    final actions = _buildActions(context);
    return AlertDialog(
      backgroundColor: Colors.white,
      elevation: 0,
      title: title != null ? Text(title!) : null,
      titleTextStyle: const TextStyle(fontSize: 24, color: Colors.black),
      actionsAlignment: actions != null && actions.length > 1
          ? MainAxisAlignment.spaceAround
          : MainAxisAlignment.center,
      actions: actions,
      contentPadding:
          contentPadding ?? const EdgeInsets.only(top: 20, bottom: 8),
      content: SizedBox(
        width: width,
        child: content,
      ),
    );
  }

  List<Widget>? _buildActions(BuildContext context) {
    final widgets = <Widget>[];
    if (showCancel) {
      widgets.add(
        _AlertActionButton(
          label: cancelLabel,
          onPressed: () {
            Navigator.of(context).pop();
            onCanceled?.call();
          },
        ),
      );
    }
    if (onConfirm != null) {
      if (widgets.isNotEmpty) {
        widgets.add(
          SizedBox(
            height: 24,
            child: VerticalDivider(
              thickness: 1,
              color: Colors.black.withOpacity(.4),
            ),
          ),
        );
      }
      widgets.add(
        _AlertActionButton(
          label: confirmLabel,
          onPressed: () {
            onConfirm!.call();
          },
        ),
      );
    }

    return widgets;
  }
}

class _AlertActionButton extends StatelessWidget {
  final String label;
  final VoidCallback onPressed;

  const _AlertActionButton({
    super.key,
    required this.label,
    required this.onPressed,
  });
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 90,
      child: TextButton(
        onPressed: onPressed,
        child: Text(
          label,
          style: const TextStyle(fontSize: 18),
        ),
      ),
    );
  }
}
