import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';

/// 安全措施弹窗
class SafeFunctionDialog extends StatefulWidget {
  /// 原始数据列表，每个元素为包含 "PROTECTIVE_MEASURES" 键的 Map
  final List<Map<String, dynamic>> data;

  /// 已选中的初始数据列表
  final List<Map<String, dynamic>> initialSelectedItems;

  /// 点击确认回调，返回选中的 Map 列表
  final void Function(List<Map<String, dynamic>> selectedItems) onConfirm;

  /// 构造函数，支持传入已选中的数据
  const SafeFunctionDialog({
    Key? key,
    required this.data,
    this.initialSelectedItems = const [],
    required this.onConfirm,
  }) : super(key: key);

  @override
  State<SafeFunctionDialog> createState() => _SafeFunctionDialogState();
}

class _SafeFunctionDialogState extends State<SafeFunctionDialog> {
  /// 存放所有可选项的 Map 列表
  late final List<Map<String, dynamic>> _allItems;

  /// 存放当前被选中的 Map 列表
  late final List<Map<String, dynamic>> _selectedItems;

  @override
  void initState() {
    super.initState();
    // 初始化所有选项
    _allItems = widget.data;
    // 初始化已选中项，克隆一份避免修改原数据
    _selectedItems = List<Map<String, dynamic>>.from(widget.initialSelectedItems);
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 24),
      content: SizedBox(
        width: MediaQuery.of(context).size.width - 24,
        height: MediaQuery.of(context).size.height -
            MediaQuery.of(context).padding.top -
            MediaQuery.of(context).padding.bottom,
        child: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: _allItems.length,
                itemBuilder: (ctx, index) {
                  final item = _allItems[index];
                  final label = item['PROTECTIVE_MEASURES'] as String? ?? '';
                  final checked = _selectedItems.contains(item);
                  return CheckboxListTile(
                    controlAffinity: ListTileControlAffinity.leading,
                    contentPadding: const EdgeInsets.symmetric(horizontal: 0),
                    activeColor: Colors.blue,
                    title: Text(label, style: const TextStyle(fontSize: 14)),
                    value: checked,
                    onChanged: (value) {
                      setState(() {
                        if (value == true) {
                          _selectedItems.add(item);
                        } else {
                          _selectedItems.remove(item);
                        }
                      });
                    },
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    text: '确定',
                    height: 40,
                    backgroundColor: Colors.blue,
                    onPressed: () {
                      widget.onConfirm(_selectedItems);
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: CustomButton(
                    text: '关闭',
                    height: 40,
                    backgroundColor: Colors.grey.shade300,
                    textStyle: TextStyle(color: Colors.grey.shade600),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

/// 显示安全措施弹窗
/// [initialSelected] 可选，指定弹窗打开时的已选项
Future<void> showSafeFunctionDialog(
    BuildContext context,
    List<Map<String, dynamic>> data,
    void Function(List<Map<String, dynamic>>) onConfirm, {
      List<Map<String, dynamic>> initialSelected = const [],
    }) {
  return showDialog(
    context: context,
    barrierDismissible: false,
    builder: (_) => SafeFunctionDialog(
      data: data,
      initialSelectedItems: initialSelected,
      onConfirm: onConfirm,
    ),
  );
}