
import 'package:flutter/material.dart';

import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';

class NumCounter extends StatefulWidget {
  int num;
  final int max;
  final int min;
  final Color color;
  final Color btnColor;
  final Function(int) onChange;
  NumCounter({this.num = 0, this.max = 99, this.min = 1, this.onChange,
    this.color, this.btnColor });
  @override
  State<StatefulWidget> createState() {
    return _NumCounterState();
  }
}

class _NumCounterState extends State<NumCounter> {

  @override
  void initState() {
    super.initState();
    if (widget.num > widget.max) {
      setState(() {
        widget.num = widget.max;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: [
          _buildCountBtn(false),
          Container(
            width: 44.px,
            height: 26.px,
            margin: EdgeInsets.all(6.px),
            padding: EdgeInsets.only(top: 3.px),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6.px),
              color: widget.color == null ? Color.fromARGB(255, 228, 228, 228) : widget.color,
            ),
            child: Text("${widget.num}", style: TextStyle(fontSize: 15.px),
                textAlign: TextAlign.center),
          ),
          _buildCountBtn(true),
        ],
      ),
    );
  }

  Widget _buildCountBtn(bool add) {
    return InkWell(
      onTap: () {
        if (add) {
          setState(() {
            if (widget.num >= widget.max) return;
            widget.num ++;
          });
        } else {
          if (widget.num <=  widget.min) return;
          setState(() {
            widget.num --;
          });
        }
        if(widget.onChange != null) {
          widget.onChange(widget.num);
        }
      },
      child: Container(
        width: 26.px,
        height: 26.px,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.px),
          color: widget.btnColor == null ? DColors.back : widget.btnColor,
        ),
        child: Text(add? "+" : "-", style: TextStyle(fontSize: 18.px), textAlign: TextAlign.center),
      ),
    );
  }
}