import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';

import 'package:flyinsono/architecture/define.dart';

class PatternItemPalette extends FStatelessWidget {
  final List<Color> colors;
  final Color activeColor;
  final ValueChanged<Color>? onChanged;

  PatternItemPalette({
    required this.colors,
    required this.activeColor,
    this.onChanged,
  });

  @override
  FWidget build(BuildContext context) {
    final children = colors
        .map(
          (e) => _ColorRadio(
            color: e,
            isActive: e == activeColor,
            onClick: () {
              _changeColor(e);
            },
          ),
        )
        .toList();
    return QuickFWidget(
      Container(
        margin: const EdgeInsets.only(left: 10),
        child: Wrap(
          spacing: 8.0, // 主轴(水平)方向间距
          runSpacing: 8.0, // 纵轴（垂直）方向间距
          direction: Axis.horizontal,
          crossAxisAlignment: WrapCrossAlignment.center,
          alignment: WrapAlignment.start,
          children: children,
        ),
      ),
    );
  }

  void _changeColor(Color v) {
    onChanged?.call(v);
  }
}

class _ColorRadio extends StatelessWidget {
  static const _size = Size(40, 40);
  final Color color;
  final bool isActive;
  final VoidCallback? onClick;

  const _ColorRadio({
    required this.color,
    this.isActive = false,
    this.onClick,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onClick,
      child: CustomPaint(
        size: _size,
        painter: _CirclePainter(
          color,
          isActive: isActive,
        ),
      ),
    );
  }
}

class _CirclePainter extends CustomPainter {
  final Color color;
  final bool isActive;

  _CirclePainter(this.color, {this.isActive = false});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    final outerRadius = size.width / 2;
    final innerRadius = outerRadius - 3;

    // 绘制实心圆
    canvas.drawCircle(
        Offset(size.width / 2, size.height / 2), innerRadius, paint);

    if (isActive) {
      paint
        ..color = color
        ..style = PaintingStyle.stroke
        ..strokeWidth = 3; // 空心圆的线宽

      // 绘制空心圆
      canvas.drawCircle(
          Offset(size.width / 2, size.height / 2), outerRadius, paint);
    }
  }

  @override
  bool shouldRepaint(_CirclePainter oldDelegate) {
    return isActive != oldDelegate.isActive || color != oldDelegate.color;
  }
}
