import 'package:flutter/material.dart';

/// 自定义数字键盘
///
/// 使用示例：
/// ```dart
/// final result = await NumericKeyboard.show(
///   context,
///   initialValue: '25',
///   decimalEnabled: true, // 温度带小数点，其他设置为 false
/// );
/// if (result != null) {
///   // 使用 result 更新设定值
/// }
/// ```
class NumericKeyboard extends StatefulWidget {
  const NumericKeyboard({
    super.key,
    required this.initialValue,
    this.decimalEnabled = false,
    this.onChanged,
    this.onConfirm,
  });

  /// 初始显示值
  final String initialValue;

  /// 是否允许输入小数点（温度模式为 true）
  final bool decimalEnabled;

  /// 输入变化回调（可选）
  final ValueChanged<String>? onChanged;

  /// 确认按钮回调（可选，配合页面内嵌使用）
  final ValueChanged<String>? onConfirm;

  /// 弹出数字键盘并返回用户确认的值
  ///
  /// [context] 构建上下文
  /// [initialValue] 初始值，默认为空字符串
  /// [decimalEnabled] 是否启用小数点输入，默认为 false
  ///
  /// 返回用户点击确认时的字符串，或 null（如退回/关闭）
  static Future<String?> show(
    BuildContext context, {
    String initialValue = '',
    bool decimalEnabled = false,
  }) {
    return showModalBottomSheet<String>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black54,
      builder: (_) => NumericKeyboard(
        initialValue: initialValue,
        decimalEnabled: decimalEnabled,
      ),
    );
  }

  @override
  State<NumericKeyboard> createState() => _NumericKeyboardState();
}

class _NumericKeyboardState extends State<NumericKeyboard> {
  late String _text;

  bool get _hasDecimal => _text.contains('.');

  @override
  void initState() {
    super.initState();
    _text = widget.initialValue;
  }

  void _onKeyTap(String key) {
    setState(() {
      switch (key) {
        case '⌫':
          if (_text.isNotEmpty) {
            _text = _text.substring(0, _text.length - 1);
          }
          break;
        case 'C':
          _text = '';
          break;
        case 'OK':
          // 确认时调用回调或关闭弹窗
          if (widget.onConfirm != null) {
            widget.onConfirm!(_text);
          } else {
            Navigator.of(context).pop(_text);
          }
          return; // 不触发 onChanged 和后续 setState 中的 pop
        case '.':
          if (!widget.decimalEnabled || _hasDecimal) return;
          if (_text.isEmpty) {
            _text = '0.';
          } else {
            _text = '$_text.';
          }
          break;
        default:
          // 数字 0-9
          // 避免前导零（除非是 "0." 开头）
          if (_text == '0' && key != '.') {
            _text = key;
          } else {
            _text = '$_text$key';
          }
          break;
      }
    });
    if (key != 'OK') {
      widget.onChanged?.call(_text);
    }
  }

  @override
  Widget build(BuildContext context) {
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    return Container(
      padding: EdgeInsets.fromLTRB(18, 18, 18, bottomPadding + 14),
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFF0D3558),
            Color(0xFF06192F),
          ],
        ),
        border: Border(
          top: BorderSide(color: Color(0xFF7BD5FF), width: 1.5),
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0x8000A8FF),
            blurRadius: 22,
            offset: Offset(0, -6),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildHandle(),
            const SizedBox(height: 14),
            _buildDisplayArea(),
            const SizedBox(height: 10),
            _buildKeypad(),
          ],
        ),
      ),
    );
  }

  Widget _buildHandle() {
    return Container(
      width: 78,
      height: 4,
      decoration: BoxDecoration(
        color: const Color(0xFF79D7FF).withValues(alpha: 0.72),
        borderRadius: BorderRadius.circular(2),
      ),
    );
  }

  Widget _buildDisplayArea() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 58,
            alignment: Alignment.centerRight,
            padding: const EdgeInsets.symmetric(horizontal: 18),
            decoration: BoxDecoration(
              color: const Color(0xFF041126),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: const Color(0xFF58BCEB), width: 1.2),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x4000A8FF),
                  blurRadius: 14,
                  offset: Offset(0, 0),
                ),
              ],
            ),
            child: Text(
              _text.isEmpty ? '0' : _text,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                fontSize: 30,
                height: 1,
                fontWeight: FontWeight.w700,
                color: Color(0xFFEAF9FF),
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        SizedBox(
          width: 104,
          height: 58,
          child: Material(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(8),
            child: InkWell(
              borderRadius: BorderRadius.circular(8),
              onTap: () => _onKeyTap('OK'),
              child: Ink(
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [
                      Color(0xFF25D8FF),
                      Color(0xFF1577D8),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0xFFB6F4FF)),
                  boxShadow: const [
                    BoxShadow(
                      color: Color(0x6625D8FF),
                      blurRadius: 16,
                    ),
                  ],
                ),
                child: const Center(
                  child: Text(
                    '确定',
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.white,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildKeypad() {
    // 按键定义：行列表，每行包含(标签, 宽度比例, 颜色类型)
    final keys = <List<_KeyDef>>[
      [
        const _KeyDef('1', 1),
        const _KeyDef('2', 1),
        const _KeyDef('3', 1),
        const _KeyDef('⌫', 1, isAction: true),
      ],
      [
        const _KeyDef('4', 1),
        const _KeyDef('5', 1),
        const _KeyDef('6', 1),
        const _KeyDef('C', 1, isAction: true),
      ],
      [
        const _KeyDef('7', 1),
        const _KeyDef('8', 1),
        const _KeyDef('9', 1),
        const _KeyDef('', 1),
      ],
      [
        if (widget.decimalEnabled) const _KeyDef('.', 1),
        _KeyDef('0', widget.decimalEnabled ? 2 : 3),
        const _KeyDef('', 1),
      ],
    ];

    return Padding(
      padding: const EdgeInsets.only(top: 2),
      child: Column(
        children: keys.map((row) {
          return Row(
            children: row.map((keyDef) {
              if (keyDef.label.isEmpty) {
                return const Spacer(flex: 1);
              }
              return Expanded(
                flex: keyDef.flex,
                child: Padding(
                  padding: const EdgeInsets.all(5),
                  child: _buildKeyButton(keyDef),
                ),
              );
            }).toList(),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildKeyButton(_KeyDef keyDef) {
    final isAction = keyDef.isAction;
    return SizedBox(
      height: 60,
      child: Material(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        child: InkWell(
          borderRadius: BorderRadius.circular(8),
          onTap: () => _onKeyTap(keyDef.label),
          child: Ink(
            decoration: BoxDecoration(
              color: isAction
                  ? const Color(0xFF10385D)
                  : const Color(0xFF092849),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: isAction
                    ? const Color(0xFF5D9EC5)
                    : const Color(0xFF3F9ED2),
                width: 1,
              ),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x2600A8FF),
                  blurRadius: 10,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Center(
              child: Text(
                keyDef.label,
                style: TextStyle(
                  fontSize: isAction ? 20 : 25,
                  fontWeight: isAction ? FontWeight.w600 : FontWeight.w700,
                  color: isAction
                      ? const Color(0xFFB8E7FF)
                      : const Color(0xFFEAF9FF),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// 键盘按键定义
class _KeyDef {
  final String label;
  final int flex;
  final bool isAction;
  const _KeyDef(this.label, this.flex, {this.isAction = false});
}
