import 'package:custom_radio_grouped_button/custom_radio_grouped_button.dart';
import 'package:daciapackete/globals.dart' as globals; // Keep this if you still need globals elsewhere in this file
import 'package:daciapackete/speicherdaten.dart';
import 'package:flutter/material.dart';
import "main.dart";
import 'package:daciapackete/config.dart'; // Import Config class

class CardLadebegrenzung extends StatefulWidget {
  final Config config; // Receive the local config
  final ValueChanged<Config>? onLadebegrenzungChanged; // Callback

  const CardLadebegrenzung({
    Key? key,
    required this.config,
    this.onLadebegrenzungChanged,
  }) : super(key: key);

  @override
  State<CardLadebegrenzung> createState() => _CardLadebegrenzungState();
}

class _CardLadebegrenzungState extends State<CardLadebegrenzung> {

  // Use widget.config to access the config object
  late List<int> _ladebegrenzungValues;
  late int _selectedLadebegrenzung;

  @override
  void initState() {
    super.initState();
    _updateLocalState();
  }

  @override
  void didUpdateWidget(covariant CardLadebegrenzung oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.config != oldWidget.config) {
      _updateLocalState();
    }
  }

  void _updateLocalState() {
    _ladebegrenzungValues = [
      widget.config.ladebegrenzungB1,
      widget.config.ladebegrenzungB2,
      widget.config.ladebegrenzungB3,
      widget.config.ladebegrenzungB4,
      widget.config.ladebegrenzungB5,
      widget.config.ladebegrenzungB6,
    ];
    _selectedLadebegrenzung = widget.config.ladebegrenzung;
  }


  void begrenzungSchreiben(int index, String neuerWert) {
    int parsedValue = int.parse(neuerWert);
    Config updatedConfig = widget.config.copy(); // Create a mutable copy to modify

    switch (index) {
      case 0:
        updatedConfig.ladebegrenzungB1 = parsedValue;
        break;
      case 1:
        updatedConfig.ladebegrenzungB2 = parsedValue;
        break;
      case 2:
        updatedConfig.ladebegrenzungB3 = parsedValue;
        break;
      case 3:
        updatedConfig.ladebegrenzungB4 = parsedValue;
        break;
      case 4:
        updatedConfig.ladebegrenzungB5 = parsedValue;
        break;
      case 5:
        updatedConfig.ladebegrenzungB6 = parsedValue;
        break;
    }
    // Update the selected value if the changed button was the selected one
    if (_ladebegrenzungValues.indexOf(_selectedLadebegrenzung) == index) {
      updatedConfig.ladebegrenzung = parsedValue;
    }

    // Call the callback to update the parent's state
    if (widget.onLadebegrenzungChanged != null) {
      widget.onLadebegrenzungChanged!(updatedConfig);
    }
  }

  @override
  Widget build(BuildContext context) {
    List<String> buttonLabels = _ladebegrenzungValues.map((e) => "$e").toList();
    int selectedIndex = _ladebegrenzungValues.indexOf(_selectedLadebegrenzung);


    void _onLongPress(int index) async {
      final newLabel = await showDialog<String>(
        context: context,
        builder: (BuildContext context) {
          String currentLabel = buttonLabels[index];
          TextEditingController _controller = TextEditingController(text: currentLabel);
          return AlertDialog(
            title: Text(context.sp.beschriftungAendern),
            content: TextFormField(
              controller: _controller,
              keyboardType: TextInputType.number,
              maxLength: 3,
              autofocus: true,
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context, _controller.text);
                },
                child: Text(context.sp.ok),
              ),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(context.sp.abbrechen),
              ),
            ],
          );
        },
      );

      if (newLabel != null && newLabel.isNotEmpty) {
        setState(() {
          begrenzungSchreiben(index, newLabel);
          // The parent will rebuild this widget with the new config,
          // so _updateLocalState will be called to refresh values.
        });
      }
    }


    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            ListTile(
              title: Text(context.sp.ladebegrenzung),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(_ladebegrenzungValues.length, (index) {
                bool isSelected = selectedIndex == index;
                return Padding(
                  padding: EdgeInsets.zero,
                  child: GestureDetector(
                    onTap: () {
                      Config updatedConfig = widget.config.copy();
                      updatedConfig.ladebegrenzung = _ladebegrenzungValues[index];
                      if (widget.onLadebegrenzungChanged != null) {
                        widget.onLadebegrenzungChanged!(updatedConfig);
                      }
                    },
                    onLongPress: () => _onLongPress(index),
                    child: Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: isSelected ? Colors.blue : Colors.grey,
                        borderRadius: BorderRadius.circular(2),
                      ),
                      child: Text(
                        buttonLabels[index],
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}