import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_operate_panel/adjust_panel_config.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:fis_theme/theme.dart';

class ControlItemUrmPostProcessingParameters extends StatefulWidget {
  const ControlItemUrmPostProcessingParameters({
    super.key,
    required this.values,
    required this.currentValue,
    this.onChanged,
    this.onDeleted,
    this.onNewPostProcess,
    this.onSavePostProcess,
    this.isShowSaveButton = false,
  });

  final List<UserUrmConfigInfo> values;
  final String currentValue;
  final ValueChanged? onChanged;
  final ValueChanged? onDeleted;
  final Function? onNewPostProcess;
  final Function? onSavePostProcess;
  final bool isShowSaveButton;

  @override
  State<StatefulWidget> createState() {
    return _ControlItemUrmProcessingParametersState();
  }
}

class _ControlItemUrmProcessingParametersState
    extends State<ControlItemUrmPostProcessingParameters> {
  late String _currentValue;
  late List<UserUrmConfigInfo> _values;

  @override
  void initState() {
    super.initState();
    _currentValue = widget.currentValue;
    _values = widget.values;
  }

  @override
  void didUpdateWidget(ControlItemUrmPostProcessingParameters oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentValue != _currentValue) {
      _currentValue = widget.currentValue;
    }
    if (widget.values != _values) {
      _values = widget.values;
    }
  }

  void _deleteItem(String code) {
    var dataSource = _values.firstWhere((element) => element.code == code);
    setState(() {
      _values.remove(dataSource);
      // 如果删除的是当前选中项，更新 _currentValue
      if (_currentValue == code) {
        _currentValue = _values.isEmpty
            ? '' // 或者设置为默认值或第一个项的 code
            : _values[0].code;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      decoration: BoxDecoration(
        color: LabColors.base200,
        borderRadius: BorderRadius.circular(3),
        border: Border.all(
          color: LabColors.base400,
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  '参数预设',
                  style: TextStyle(
                    fontSize: 12,
                    height: 1,
                    color: LabColors.text700,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Row(
                children: [
                  if (widget.onSavePostProcess != null &&
                      !widget.isShowSaveButton)
                    MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: GestureDetector(
                        onTap: () {
                          widget.onSavePostProcess!();
                        },
                        child: Text(
                          '保存预设',
                          style: TextStyle(
                            color: Colors.white, // 将颜色改为白色
                            decoration: TextDecoration.underline,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  SizedBox(width: 10), // 添加空间
                  if (widget.onNewPostProcess != null)
                    MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: GestureDetector(
                        onTap: () {
                          widget.onNewPostProcess!();
                        },
                        child: Text(
                          '新建预设',
                          style: TextStyle(
                            color: Colors.white, // 将颜色改为白色
                            decoration: TextDecoration.underline,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ],
          ),
          SizedBox(height: 10),
          Container(
            height: 40,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: LabBoxDecoration.operatePanel,
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  key: GlobalKey(),
                  value: _currentValue,
                  itemHeight: 50,
                  dropdownColor: LabColors.base100,
                  icon: Icon(
                    Icons.keyboard_arrow_down_rounded,
                    color: LabColors.base800,
                  ),
                  style: TextStyle(
                    fontSize: 14,
                    color: LabColors.text800,
                    fontFamily: FTheme.ins.localeSetting.fontFamily,
                  ),
                  isExpanded: true,
                  elevation: 2,
                  items: _values.map((e) => e.code).toList().map((String code) {
                    var dataSource =
                        _values.firstWhere((element) => element.code == code);
                    return DropdownMenuItem<String>(
                        value: code,
                        child: Row(
                          children: [
                            Expanded(
                              child: Text(
                                itemToString(code),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                            ),
                            if (!(_currentValue == code ||
                                dataSource.isDefault))
                              IconButton(
                                onPressed: () {
                                  _deleteItem(code);
                                  widget.onDeleted?.call(dataSource.code);
                                },
                                icon: Icon(
                                  Icons.delete,
                                  color: LabColors.base800,
                                ),
                                style: ButtonStyle(
                                  iconColor: MaterialStateProperty.all<Color>(
                                      LabColors.base800),
                                ),
                              ),
                          ],
                        ));
                  }).toList(),
                  onChanged: (value) {
                    if (value != null) {
                      setState(() {
                        _currentValue = value;
                      });
                      widget.onChanged?.call(value);
                    }
                  },
                ),
              ),
            ),
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }

  String itemToString(String code) {
    var dto = _values.where((element) => element.code == code).first;
    return dto.configName;
  }
}
