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

import '../alert_dialog.dart';
import 'group.dart';

class VDialogRadioCellGroup<T, TValue> extends StatefulWidget {
  final String? title;
  final List<RadioCellGroupItem<T>> source;

  /// 选项文本提取函数
  final String Function(T data) labelGetter;

  /// 选项值提取函数
  final TValue Function(T data) valueGetter;

  final VRadioCellGroupCheckChanged<T, TValue>? onChanged;

  const VDialogRadioCellGroup({
    super.key,
    this.title,
    required this.source,
    required this.labelGetter,
    required this.valueGetter,
    this.onChanged,
  });

  Future<List<V>> show<V>() async {
    final result = await VAlertDialog.showDialog<List<V>>(this);
    return result!;
  }

  @override
  State<StatefulWidget> createState() => _DialogGroupState<T, TValue>();
}

class _DialogGroupState<T, TValue>
    extends State<VDialogRadioCellGroup<T, TValue>> {
  late TValue? _value;

  @override
  void initState() {
    _value = widget.source
        .where((e) => e.isChecked)
        .map((e) => widget.valueGetter.call(e.data))
        .first;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return VAlertDialog(
      title: widget.title,
      // contentPadding: EdgeInsets.symmetric(horizontal: 20),
      content: Scrollbar(
        thumbVisibility: true,
        child: VRadioCellGroup<T, TValue>(
          labelGetter: widget.labelGetter,
          valueGetter: widget.valueGetter,
          source: widget.source,
          onChanged: (value, isChecked, data, checkedValue) {
            _value = checkedValue;
            widget.onChanged?.call(value, isChecked, data, checkedValue);
          },
          isScrollable: true,
        ),
      ),
      onConfirm: () {
        Get.back(result: _value);
      },
    );
  }
}
