import 'package:flutter/material.dart';

class DualRadialGradientBorderPainter extends CustomPainter {
  final double strokeWidth;
  final BorderRadius borderRadius;
  final RadialGradient leftToRightGradient;
  final RadialGradient rightToLeftGradient;
  final Color? backgroundColor;

  DualRadialGradientBorderPainter({
    this.strokeWidth = 1,
    double? radius,
    BorderRadius? borderRadius,
    required this.leftToRightGradient,
    required this.rightToLeftGradient,
    this.backgroundColor,
  }) : borderRadius = borderRadius ?? BorderRadius.circular(radius ?? 100);

  @override
  void paint(Canvas canvas, Size size) {
    final Rect rect = Rect.fromLTWH(
      strokeWidth / 2,
      strokeWidth / 2,
      size.width - strokeWidth,
      size.height - strokeWidth,
    );

    final RRect rrect = RRect.fromRectAndCorners(
      rect,
      topLeft: borderRadius.topLeft,
      topRight: borderRadius.topRight,
      bottomLeft: borderRadius.bottomLeft,
      bottomRight: borderRadius.bottomRight,
    );

    // 如果有背景色，先绘制背景
    if (backgroundColor != null) {
      final Paint backgroundPaint = Paint()
        ..style = PaintingStyle.fill
        ..color = backgroundColor!;
      canvas.drawRRect(rrect, backgroundPaint);
    }

    // 绘制第一层径向渐变边框 - 从左到右
    final Paint leftToRightPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..shader = leftToRightGradient.createShader(rect);
    canvas.drawRRect(rrect, leftToRightPaint);

    // 绘制第二层径向渐变边框 - 从右到左
    final Paint rightToLeftPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..shader = rightToLeftGradient.createShader(rect);
    canvas.drawRRect(rrect, rightToLeftPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class DualRadialGradientBorderContainer extends StatelessWidget {
  final Widget child;
  final double strokeWidth;
  final BorderRadius borderRadius;
  final RadialGradient leftToRightGradient;
  final RadialGradient rightToLeftGradient;
  final Color? backgroundColor;
  final EdgeInsetsGeometry padding;

  DualRadialGradientBorderContainer({
    super.key,
    required this.child,
    required this.leftToRightGradient,
    required this.rightToLeftGradient,
    this.strokeWidth = 1,
    double? radius,
    BorderRadius? borderRadius,
    this.padding = const EdgeInsets.all(8),
    this.backgroundColor,
  }) : borderRadius = borderRadius ?? BorderRadius.circular(radius ?? 100);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: DualRadialGradientBorderPainter(
        strokeWidth: strokeWidth,
        borderRadius: borderRadius,
        leftToRightGradient: leftToRightGradient,
        rightToLeftGradient: rightToLeftGradient,
        backgroundColor: backgroundColor,
      ),
      child: Container(
        padding: padding,
        child: child,
      ),
    );
  }
}
