import 'package:aman_kassa_flutter/redux/actions/kassa_actions.dart';
import 'package:aman_kassa_flutter/redux/store.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:aman_kassa_flutter/shared/ui_helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ProductAddBottomSheet extends StatefulWidget {
  final ScrollController scrollController;

  ProductAddBottomSheet({this.scrollController});

  @override
  _ProductAddBottomSheetState createState() => _ProductAddBottomSheetState();
}

class _ProductAddBottomSheetState extends State<ProductAddBottomSheet> {
  TextEditingController nameController;
  TextEditingController countController;
  TextEditingController priceController;
  double sum = 0.0;

  @override
  void initState() {
    super.initState();
    nameController = new TextEditingController();
    countController = new TextEditingController();
    priceController = new TextEditingController();
  }

  @override
  void dispose() {
    nameController.dispose();
    countController.dispose();
    priceController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: whiteColor),
      child: Scaffold(
        appBar: AppBar(
          iconTheme: IconThemeData(color: Colors.black),
          backgroundColor: fillColor,
          elevation: 3,
          title: Text(
            'Добавить товар/услугу',
            style: TextStyle(color: Colors.black87),
          ),
        ),
        body: Padding(
          padding: EdgeInsets.only(top: 15, left: 10, right: 15, bottom: 0 ),
          child: ListView(
            controller: widget.scrollController,
            children: <Widget>[
              TextField(
                decoration: new InputDecoration(
                  border: new OutlineInputBorder(
                      borderSide: new BorderSide(color: primaryColor)),
                  hintText: 'Введите наименовение',
                  labelText: 'Наименование',
                  prefixText: ' ',
                ),
                controller: nameController,
              ),
              verticalSpaceSmall,
              TextField(
                decoration: new InputDecoration(
                  border: new OutlineInputBorder(
                      borderSide: new BorderSide(color: primaryColor)),
                  hintText: 'Введите количество',
                  labelText: 'Количество',
                  prefixText: ' ',
                ),
                keyboardType: const TextInputType.numberWithOptions(
                  decimal: false,
                ),
                inputFormatters: <TextInputFormatter>[
                  // WhitelistingTextInputFormatter.digitsOnly
                  FilteringTextInputFormatter.digitsOnly
                ],
                controller: countController,
                onChanged: calcOnChange,
              ),
              verticalSpaceSmall,
              TextField(
                decoration: new InputDecoration(
                  border: new OutlineInputBorder(
                      borderSide: new BorderSide(color: primaryColor)),
                  hintText: 'Введите цену за единицу',
                  labelText: 'Стоимость',
                  prefixText: ' ',
                ),
                keyboardType:
                    const TextInputType.numberWithOptions(decimal: true),
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.allow(RegExp("^[0-9.]*")),
                ],
                controller: priceController,
                onChanged: calcOnChange,
              ),
              const Divider(
                height: 1.0,
              ),
              new ListTile(
                leading: const Icon(
                  Icons.account_balance_wallet,
                  color: primaryColor,
                ),
                title: Text(sum == 0 ? '' : sum.toString()),
                subtitle: const Text('Стоимость'),
              ),
              verticalSpaceMedium,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  RawMaterialButton(
                    onPressed: submit,
                    elevation: 2.0,
                    fillColor: greenColor,
                    child: Icon(
                      Icons.done,
                      size: 35.0,
                      color: whiteColor,
                    ),
                    padding: EdgeInsets.all(15.0),
                    shape: CircleBorder(),
                  ),
                  RawMaterialButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    elevation: 2.0,
                    fillColor: redColor,
                    child: Icon(
                      Icons.close,
                      size: 35.0,
                      color: whiteColor,
                    ),
                    padding: EdgeInsets.all(15.0),
                    shape: CircleBorder(),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  void submit() {
    if (nameController.text.isEmpty ||
        countController.text.isEmpty ||
        priceController.text.isEmpty) {
      _showDialog();
    } else {
      Redux.store.dispatch(addCustomProductToKassaItems(
          nameController.text,
          int.parse(countController.text),
          double.parse(priceController.text),
          sum));
      Navigator.pop(context);
    }
  }

  void calcOnChange(value) {
    try {
      setState(() {
        sum = 0;
      });
      if (countController.text != '' && priceController.text != '') {
        double count = double.parse(countController.text);
        double price = double.parse(priceController.text);
        double result = count * price;
        setState(() {
          sum = ((result * 100).roundToDouble()) / 100;
        });
      }
    } catch (e) {
      print(e);
    }
  }

  void _showDialog() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Aman Касса"),
          content: new Text("Введите наименование, количество и цену"),
          actions: <Widget>[
            FlatButton(
              child: Text(
                "ОK",
                style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
