import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/PharmacyProduct.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/product_detail_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart';
import 'package:diplomaticquarterapp/pages/pharmacies/screens/product-details/footor/quantity_box.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/material.dart';

import '../../../../../locator.dart';
import '../../../../../routes.dart';

class FooterWidget extends StatefulWidget {
  final bool isAvailable;
  final int maxQuantity;
  final int minQuantity;
  final int quantityLimit;
  final PharmacyProduct item;
  final Function addToCartFunction;
  final Function addToShoppingCartFunction;
  final ProductDetailViewModel model;

  int quantity;
  bool isOverQuantity;

  FooterWidget(this.isAvailable, this.maxQuantity, this.minQuantity,
      this.quantityLimit, this.item,
      {this.quantity,
      this.isOverQuantity = false,
      this.addToCartFunction,
      this.addToShoppingCartFunction,
      this.model});

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

class _FooterWidgetState extends State<FooterWidget> {
  double quantityUI = 80;
  bool showUI = false;

  static final GlobalKey<FormState> _key = GlobalKey<FormState>();
  AuthenticatedUserObject authenticatedUserObject =
      locator<AuthenticatedUserObject>();
  AppSharedPreferences sharedPref = new AppSharedPreferences();

  @override
  void initState() {
    super.initState();
    if (!isBuyNowDisable() || !isAddToCartDisable()) {
      quantityUI = 160;
      showUI = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(
          Radius.circular(0.0),
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFCCCCCC),
            spreadRadius: 0,
            blurRadius: 4,
            offset: Offset(2, 2), // changes position of shadow
          ),
        ],
        // border: Border.all(color: Color(0xFF707070), width: 0),
      ),
      width: double.infinity,
      height: quantityUI,
      child: Column(
        children: [
          !showUI
              ? Container(
                  height: 10,
                )
              : Container(
                  width: double.infinity,
                  height: 100,
                  color: Colors.white,
                  child: Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Texts(
                                  TranslationBase.of(context).productQuantity,
                                  fontSize: 15,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFF575757)),
                            ),
                            InkWell(
                              child: Icon(Icons.close, color: Colors.black),
                              onTap: () {
                                setState(() {
                                  quantityUI = 80;
                                  showUI = false;
                                });
                              },
                            )
                          ],
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        ),
                        Container(
                          height: 35.0,
                          child: ListView(
                            scrollDirection: Axis.horizontal,
                            children: <Widget>[
                              SizedBox(
                                width: 5,
                              ),
                              for (int i = 1; i <= 10; i++)
                                QuantityBox(
                                    label: i,
                                    onTapFunc: onChangeValue,
                                    isSelected: widget.quantity == i),
                              Container(
                                width: 100,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey[300]),
                                  color: Colors.white,
                                ),
                                child: TextField(
                                  key: _key,
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.center,
                                  decoration:
                                      InputDecoration(hintText: ' Quantity # '),
                                  onChanged: (text) {
                                    if (int.tryParse(text) == null) {
                                      text = '';
                                    } else {
                                      setState(() {
                                        widget.quantity = int.parse(text);
                                        if (widget.quantity >=
                                            widget.quantityLimit) {
                                          widget.isOverQuantity = true;
                                        } else {
                                          widget.isOverQuantity = false;
                                        }
                                      });
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
          Container(
            height: 58,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 60,
                  child: FlatButton(
                    child: Row(
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppText(
                              TranslationBase.of(context).productQuantity,
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                            ),
                            Row(
                              children: [
                                AppText(
                                  widget.quantity.toString(),
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Icon(
                                  Icons.keyboard_arrow_down,
                                  color: Color(0xFF2E303A),
                                  size: 25,
                                )
                              ],
                            ),
                          ],
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        SizedBox(
                          height: 40,
                          width: 1,
                          child: Container(
                            color: Color(0xFFEFEFEF),
                          ),
                        ),
                      ],
                    ),
                    onPressed: widget.isAvailable && !widget.item.isRx
                        ? () {
                            setState(() {
                              if (showUI) {
                                quantityUI = 80;
                                showUI = false;
                              } else {
                                quantityUI = 160;
                                showUI = true;
                              }
                            });
                          }
                        : null,
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.35,
                  margin: EdgeInsets.symmetric(vertical: 4.0),
                  child: SecondaryButton(
                    label: TranslationBase.of(context).addToCart,
                    disabled: isAddToCartDisable(),
                    fontSize: 15,
                    onTap: () async {
                      if (!authenticatedUserObject.isLogin) {
                        login();
                      } else
                        await widget.addToCartFunction(
                            quantity: widget.quantity,
                            itemID: widget.item.id,
                            model: widget.model);
                    },
                    fontWeight: FontWeight.w600,
                    borderRadius: 6,
                    disableColor: Color(0xFFD6D6D6),
                    textColor:
                        isAddToCartDisable() ? Color(0xFFACACAC) : Colors.white,
                    color: Color(0xFF535353),
                  ),
                ),
                SizedBox(
                  width: 5,
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.35,
                  margin: EdgeInsets.symmetric(vertical: 4.0),
                  child: SecondaryButton(
                    label: TranslationBase.of(context).buyNow,
                    fontSize: 15,
                    disabled: isBuyNowDisable(),
                    onTap: () async {
                      if (!authenticatedUserObject.isLogin) {
                        login();
                      } else {
                        await widget.addToShoppingCartFunction(
                            quantity: widget.quantity,
                            itemID: widget.item.id,
                            model: widget.model);
                      }
                    },
                    textColor:
                        isBuyNowDisable() ? Color(0xFFACACAC) : Colors.white,
                    fontWeight: FontWeight.w600,
                    borderRadius: 6,
                    disableColor: Color(0xFFD6D6D6),
                    color: Color(0xFF5AB145),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  bool isBuyNowDisable() {
    return (!widget.isAvailable && widget.quantity > 0) ||
        (widget.quantity > widget.quantityLimit) ||
        widget.item.isRx;
  }

  bool isAddToCartDisable() {
    return (!widget.isAvailable && widget.quantity > 0) ||
        widget.quantity > widget.quantityLimit ||
        widget.item.isRx;
  }

  void setUserValues(value) async {
    if (value != null) sharedPref.setObject(IMEI_USER_DATA, value);
  }

  login() async {
    final authService = new AuthProvider();
    var data = await sharedPref.getObject(IMEI_USER_DATA);
    sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);
    if (data != null) {
      Navigator.of(context).pushNamed(CONFIRM_LOGIN);
    } else {
      GifLoaderDialogUtils.showMyDialog(context);
      authService
          .selectDeviceImei(DEVICE_TOKEN)
          .then((SelectDeviceIMEIRES value) {
        GifLoaderDialogUtils.hideDialog(context);
        if (value != null) {
          setUserValues(value);
          Navigator.of(context).pushNamed(CONFIRM_LOGIN);
        } else {
          Navigator.of(context).pushNamed(
            WELCOME_LOGIN,
          );
        }
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.of(context).pushNamed(
          WELCOME_LOGIN,
        );
      });
    }
  }

  onChangeValue(int i) {
    setState(() {
      widget.quantity = i;
      if (widget.quantity >= widget.quantityLimit) {
        widget.isOverQuantity = true;
      } else {
        widget.isOverQuantity = false;
        return widget.quantity;
      }
    });
  }
}
