import 'package:flutter/material.dart';

enum VButtonType {
  primary,
  error,
  cancel,
  text,
}

class VButton extends StatelessWidget {
  /// 类型
  final VButtonType type;

  /// 文字
  final String? label;

  /// 自定义子组件
  final Widget? child;

  /// 点击事件回调
  final VoidCallback? onTap;

  const VButton({
    super.key,
    this.type = VButtonType.primary,
    this.label,
    this.child,
    this.onTap,
  }) : assert(label != null || child != null);

  @override
  Widget build(BuildContext context) {
    final colors = _findBgColor(context, type);
    final bgColor = colors.$1;
    final textColor = colors.$2;

    return LayoutBuilder(builder: (context, c) {
      double width = c.maxWidth;
      if (width > 1200) {
        width = 270;
      }
      double height = c.maxHeight;
      if (height > 720) {
        height = 60;
      }
      double radius = height / 2;
      return SizedBox(
        width: 270,
        height: height,
        child: ElevatedButton(
          onPressed: () {
            onTap?.call();
          },
          style: ButtonStyle(
            foregroundColor: MaterialStatePropertyAll(textColor),
            backgroundColor: MaterialStatePropertyAll(bgColor),
            elevation: const MaterialStatePropertyAll(0),
            padding: MaterialStatePropertyAll(
              EdgeInsets.symmetric(horizontal: radius, vertical: 8),
            ),
            alignment: Alignment.center,
            shape: MaterialStatePropertyAll(
              RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(radius),
              ),
            ),
          ),
          child: child ??
              Text(
                label!,
                style: TextStyle(
                  color: textColor,
                  fontSize: 18,
                ),
              ),
        ),
      );
    });
  }

  (Color c, Color b) _findBgColor(BuildContext context, VButtonType type) {
    switch (type) {
      case VButtonType.primary:
        return (Theme.of(context).primaryColor, Colors.white);
      case VButtonType.error:
        return (Theme.of(context).colorScheme.error, Colors.white);
      case VButtonType.text:
        return (Colors.white, Theme.of(context).primaryColor);
      case VButtonType.cancel:
        return (Colors.grey, Colors.white);
    }
  }
}
