import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';

class NumberPad extends StatefulWidget {
  const NumberPad({
    super.key,
    required this.title,
    required this.maxFrame,
    this.onNumberValueChange,
    required this.minFrame,
    required this.currentValue,
    this.interval = 1,
  });

  final String title;
  final int minFrame;
  final int maxFrame;
  final int currentValue;
  final int interval;
  final ValueChanged<int>? onNumberValueChange;

  @override
  State<NumberPad> createState() => _NumberPadState();
}

class _NumberPadState extends State<NumberPad> {
  late TextEditingController _controller;
  late FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.currentValue.toString());
    _focusNode = FocusNode();
    _focusNode.addListener(_onFocusChange);
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.removeListener(_onFocusChange);
    _focusNode.dispose();
    super.dispose();
  }

  void _onFocusChange() {
    if (!_focusNode.hasFocus) {
      _validateAndUpdateValue();
    }
  }

  void _validateAndUpdateValue() {
    String input = _controller.text.trim();

    if (input.isEmpty) {
      PromptBox.toast('请输入一个有效的数字');
      _resetToCurrentValue();
      return;
    }

    int? value = int.tryParse(input);

    if (value == null) {
      PromptBox.toast('请输入一个有效的整数');
      _resetToCurrentValue();
    } else if (value < widget.minFrame) {
      PromptBox.toast('值不能小于 ${widget.minFrame}');
      _resetToCurrentValue(recommendedValue: widget.minFrame);
    } else if (value > widget.maxFrame) {
      PromptBox.toast('值不能大于 ${widget.maxFrame}');
      _resetToCurrentValue(recommendedValue: widget.maxFrame);
    } else {
      widget.onNumberValueChange?.call(value);
    }
  }

  void _resetToCurrentValue({int? recommendedValue}) {
    if (recommendedValue != null) {
      _controller.text = recommendedValue.toString();
    } else {
      _controller.text = widget.currentValue.toString();
    }
  }

  void _increment() {
    int currentValue = int.parse(_controller.text);
    int newValue = currentValue + widget.interval;
    if (newValue <= widget.maxFrame) {
      _controller.text = newValue.toString();
      widget.onNumberValueChange?.call(newValue);
    } else {
      PromptBox.toast('已达最大值！');
    }
  }

  void _decrement() {
    int currentValue = int.parse(_controller.text);
    int newValue = currentValue - widget.interval;
    if (newValue >= widget.minFrame) {
      _controller.text = newValue.toString();
      widget.onNumberValueChange?.call(newValue);
    } else {
      PromptBox.toast('已达最小值！');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: LabColors.base200,
        borderRadius: BorderRadius.circular(3),
        border: Border.all(color: LabColors.base400, width: 1),
      ),
      alignment: Alignment.center,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            widget.title,
            style: TextStyle(
              fontSize: 14,
              height: 1,
              color: LabColors.text700,
            ),
          ),
          SizedBox(height: 2),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildButton(Icons.remove, _decrement),
              Expanded(
                child: TextField(
                  controller: _controller,
                  focusNode: _focusNode,
                  textAlign: TextAlign.center,
                  keyboardType: TextInputType.number,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  style: TextStyle(
                    fontSize: 14,
                    color: LabColors.base800,
                  ),
                  decoration: InputDecoration(
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(vertical: 8),
                    border: InputBorder.none,
                  ),
                  onSubmitted: (_) => _validateAndUpdateValue(),
                ),
              ),
              _buildButton(Icons.add, _increment),
            ],
          ),
          SizedBox(height: 5),
        ],
      ),
    );
  }

  Widget _buildButton(IconData icon, VoidCallback onTap) {
    return Material(
      color: Colors.transparent,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 5),
        child: InkWell(
          borderRadius: BorderRadius.circular(3),
          hoverColor: LabColors.base400,
          onTap: onTap,
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 4),
            child: Icon(
              icon,
              color: LabColors.base800,
              size: 28,
            ),
          ),
        ),
      ),
    );
  }
}
