import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/AddProductToCartRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersCategoriesRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/requests/OffersProductsRequestModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesCategoriesResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/PackagesResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/packages_offers/responses/offers_stores_response_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/packages_offers/PackagesOffersViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/h2o/h20_setting.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/ClinicOfferAndPackagesPage.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/OfferAndPackagesCartPage.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/packages_offers_tab_pager.dart';
import 'package:diplomaticquarterapp/pages/packages_offers/packages_orders_history.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart' as auth;
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/navigation_service.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart' as utils;
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesOfferCard.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';

class PackagesHomePage extends StatefulWidget {
  final AuthenticatedUser user;

  PackagesHomePage(this.user);

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

class _PackagesHomePageState extends State<PackagesHomePage> {
  ProjectViewModel projectViewModel;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      viewModel.service.patientUser = widget.user;
      viewModel.service.loadOffersPackagesDataForMainPage(
          context: context,
          completion: () {
            setState(() {});
          });
    });
  }

  // Controllers
  var _searchTextController = TextEditingController();

  ListView _listViewLatestOffers;
  ListView _listViewBestSeller;

  PackagesViewModel viewModel;

  onCartClick() {
    if (viewModel.service.customer == null) {
      utils.Utils.showErrorToast("Cart is empty for your current session");
      return;
    }
    Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => PackagesCartPage()));
  }

  onProductCartClick(PackagesResponseModel product) async {
    if (viewModel.service.customer == null) {
      // viewModel.service.customer = await CreateCustomerDialogPage(context: context).show();
      loginCheck(context);
    }

    if (viewModel.service.customer != null) {
      var request = AddProductToCartRequestModel(product_id: product.id, customer_id: viewModel.service.customer.id);
      await viewModel.service.addProductToCart(request, context: context).then((response) {}).catchError((error) {
        utils.Utils.showErrorToast(error.toString());
      });
    }
  }

  PackagesCategoriesResponseModel selectedClinic;
  OfferProject selectedProject;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return BaseView<PackagesViewModel>(
      allowAny: true,
      onModelReady: (model) => viewModel = model,
      builder: (_, model, wi) {
        return Column(
          children: [
            Expanded(
              child: ListView(
                padding: EdgeInsets.only(top: 21, bottom: 21),
                physics: BouncingScrollPhysics(),
                children: [
                  if(OFFERS_VIEW_ONLY)
                    inputWidget(TranslationBase.of(context).search, "", _searchTextController, isInputTypeNum: false),
                  SizedBox(height: 12),
                  Padding(
                    padding: const EdgeInsets.only(left: 21, right: 21),
                    child: CommonDropDownView(TranslationBase.of(context).browseOffersByProject, selectedProject?.name ?? TranslationBase.of(context).selectProject, () => showHospitalSelectionList())
                        .withBorderedContainer,
                  ),
                  SizedBox(height: 12),
                  Padding(
                    padding: const EdgeInsets.only(left: 21, right: 21),
                    child: CommonDropDownView(TranslationBase.of(context).browseOffers, selectedClinic?.name ?? TranslationBase.of(context).selectClinic, () => showClinicSelectionList())
                        .withBorderedContainer,
                  ),
                  SizedBox(height: 12),
                  Container(
                    width: double.infinity,
                    height: MediaQuery.of(context).size.width * 0.8,
                    child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      physics: BouncingScrollPhysics(),
                      padding: EdgeInsets.only(left: 21, right: 21),
                      itemCount: viewModel.bestSellerList.length,
                      separatorBuilder: (context, index) {
                        return mWidth(9.0);
                      },
                      itemBuilder: (BuildContext context, int index) {
                        return PackagesItemCard(
                          itemModel: viewModel.bestSellerList[index],
                          onCartClick: OFFERS_VIEW_ONLY ? onProductCartClick : null,
                        );
                      },
                    ),
                  ),
                  SizedBox(height: 12),
                  Container(
                    width: double.infinity,
                    height: MediaQuery.of(context).size.width * 0.8,
                    child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      physics: BouncingScrollPhysics(),
                      padding: EdgeInsets.only(left: 21, right: 21),
                      itemCount: viewModel.latestOffersList.length,
                      separatorBuilder: (context, index) {
                        return mWidth(9.0);
                      },
                      itemBuilder: (BuildContext context, int index) {
                        return PackagesItemCard(
                          itemModel: viewModel.latestOffersList[index],
                          onCartClick: OFFERS_VIEW_ONLY ? onProductCartClick : null,
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),

            if(OFFERS_VIEW_ONLY)
              DefaultButton(
                TranslationBase.of(context).myCart,
                onCartClick,
                svgIcon: "assets/images/new/cart.svg",
                isTextExpanded: false,
                count: viewModel?.service?.customer?.shoppingCartItems?.length ?? 0,
              ).insideContainer
          ],
        );
      },
    );
  }

  int _selectedClinic = -1;

  showClinicSelectionList() async {
    var clinics = await viewModel.service.getAllCategories(OffersCategoriesRequestModel());
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < clinics.length; i++) RadioSelectionDialogModel(clinics[i].name, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedClinic,
        isScrollable: true,
        onValueSelected: (index) async {
          _selectedClinic = index;
          selectedClinic = clinics[index];
          var clinicProducts = await viewModel.service.getAllProducts(request: OffersProductsRequestModel(categoryId: selectedClinic.id), context: context, showLoading: true);
          if (clinicProducts.isNotEmpty)
            Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => ClinicPackagesPage(products: clinicProducts)));
          else
            utils.Utils.showErrorToast("No offers available for this clinic");
          setState(() {});
        },
      ),
    );
  }

  int _selectedHospital = -1;

  showHospitalSelectionList() async {
    GifLoaderDialogUtils.showMyDialog(context);
    var hospitals = await viewModel.service.getAllStores();
    GifLoaderDialogUtils.hideDialog(context);

    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < hospitals.length; i++) RadioSelectionDialogModel(hospitals[i].name, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedHospital,
        isScrollable: true,
        onValueSelected: (index) async {
          _selectedHospital = index;
          selectedProject = hospitals[index];
          var request = OffersProductsRequestModel(storeId: selectedProject.id);
          request.sinceId = 0;
          var products = await viewModel.service.getAllProducts(request: request, context: context, showLoading: true);
          if (products.isNotEmpty)
            Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => ClinicPackagesPage(products: products)));
          else
            utils.Utils.showErrorToast("No offers available for this clinic");
          setState(() {});
        },
      ),
    );
  }

  //----------------------------------
  // Main Widgets of Page
  //----------------------------------

  Widget latestOfferListView({@required double itemWidth, @required double itemContentPadding}) {
    return _listViewLatestOffers = ListView.separated(
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      itemCount: viewModel.bestSellerList.length,
      itemBuilder: (BuildContext context, int index) {
        return PackagesItemCard(
          itemWidth: itemWidth,
          itemContentPadding: itemContentPadding,
          itemModel: viewModel.bestSellerList[index],
          onCartClick: onProductCartClick,
        );
      },
      separatorBuilder: separator,
    );
  }

  Widget bestSellerListView({@required double itemWidth, @required double itemContentPadding}) {
    return _listViewLatestOffers = ListView.separated(
      scrollDirection: Axis.horizontal,
      itemCount: viewModel.bestSellerList.length,
      itemBuilder: (BuildContext context, int index) {
        return PackagesItemCard(
          itemWidth: itemWidth,
          itemContentPadding: itemContentPadding,
          itemModel: viewModel.bestSellerList[index],
          onCartClick: onProductCartClick,
        );
      },
      separatorBuilder: separator,
    );
  }

  Widget separator(BuildContext context, int index) {
    return Container(
      width: 1,
      decoration: BoxDecoration(
          gradient:
              LinearGradient(begin: Alignment(-1.0, -2.0), end: Alignment(1.0, 4.0), colors: [Colors.grey, Colors.grey[100], Colors.grey[200], Colors.grey[300], Colors.grey[400], Colors.grey[500]])),
    );
  }

  loginCheck(context) async {
    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);

      auth.AuthProvider().selectDeviceImei(DEVICE_TOKEN).then((SelectDeviceIMEIRES value) {
        GifLoaderDialogUtils.hideDialog(context);
        if (value != null) {
          sharedPref.setObject(IMEI_USER_DATA, 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,
        );
      });
    }
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller,
      {VoidCallback suffixTap, bool isEnable = true, bool hasSelection = false, int lines, bool isInputTypeNum = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      margin: const EdgeInsets.only(left: 21, right: 21),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: isInputTypeNum ? TextInputType.number : TextInputType.text,
                    controller: _controller,
                    maxLines: lines,
                    onChanged: (value) => {setState(() {})},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            Icon(Icons.search_outlined),
          ],
        ),
      ),
    );
  }
}
