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

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

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

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

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

  final VCheckBoxCellGroupCheckChanged<T, TValue>? onChanged;

  const VDialogCheckBoxCellGroup({
    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<VDialogCheckBoxCellGroup<T, TValue>> {
  late List<TValue> _values;

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

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