import 'package:hmg_patient_app/core/model/pharmacies/Addresses.dart';
import 'package:hmg_patient_app/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/pages/pharmacies/screens/payment-method-select-page.dart';
import 'package:hmg_patient_app/pages/pharmacy/pharmacyAddresses/AddAddress.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/borderedButton.dart';
import 'package:hmg_patient_app/widgets/data_display/text.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

///TODO Elham* split this to tow files
class PharmacyAddressesPage extends StatefulWidget {
  final OrderPreviewViewModel? orderPreviewViewModel;
  final Function? changeMainState;

  final bool isUpdate;
  final bool isShippingAddress;

  const PharmacyAddressesPage({Key? key, this.orderPreviewViewModel, this.isUpdate = false, this.isShippingAddress = false, this.changeMainState}) : super(key: key);

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

class _PharmacyAddressesState extends State<PharmacyAddressesPage> {
  void navigateToAddressPage(BuildContext ctx, PharmacyAddressesViewModel model, AddressInfo address) {
    Navigator.push(
      ctx,
      FadePage(
        page: AddAddressPage(
          address,
          (pickResult, latLong) async {
            await model.addEditAddress(pickResult, address, latLong: latLong);
          },
        ),
      ),
    ).then((value) async {
      // await model.getAddressesList();
    });
  }

  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final height = mediaQuery.size.height - 60 - mediaQuery.padding.top;
    ProjectViewModel projectProvider = Provider.of(context);

    return BaseView<PharmacyAddressesViewModel>(
      onModelReady: (model) => model.getAddressesList(),
      builder: (_, model, wi) => AppScaffold(
        appBarTitle: widget.isUpdate ? TranslationBase.of(context).changeAddress : TranslationBase.of(context).addAddress,
        isShowAppBar: true,
        isPharmacy: true,
        baseViewModel: model,
        backgroundColor: Colors.white,
        body: Container(
          height: widget.isShippingAddress ? height * 0.90 : height * 0.99,
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                ...List.generate(
                  model.addresses != null ? model.addresses.length : 0,
                  (index) => AddressItemWidget(
                      model,
                      model.addresses[index],
                      () {
                        setState(() {
                          model.setSelectedAddressIndex(index);
                        });
                      },
                      model.selectedAddressIndex == index,
                      (address) {
                        navigateToAddressPage(context, model, address);
                      }),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.all(8),
                  child: BorderedButton(
                    TranslationBase.of(context).addAddress,
                    hasBorder: true,
                    borderColor: Color(0xFF0fca6d),
                    textColor: Color(0xFF0fca6d),
                    fontWeight: FontWeight.bold,
                    backgroundColor: Colors.white,
                    fontSize: 14,
                    vPadding: 12,
                    hasShadow: true,
                    handler: () {
                      navigateToAddressPage(context, model, AddressInfo());
                    },
                  ),
                ),
                SizedBox(
                  height: height * 0.10,
                )
              ],
            ),
          ),
        ),
        bottomSheet: widget.isShippingAddress
            ? Container(
                height: height * 0.10,
                color: Colors.white,
                child: Column(
                  children: [
                    Divider(
                      color: Colors.grey.shade300,
                      height: 1,
                      thickness: 1,
                      indent: 0,
                      endIndent: 0,
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      child: BorderedButton(
                        TranslationBase.of(context).confirmAddress,
                        hasBorder: true,
                        borderColor: Color(0xFF5AB145),
                        textColor: Colors.white,
                        fontWeight: FontWeight.bold,
                        backgroundColor: Color(0xFF5AB145),
                        fontSize: 14,
                        vPadding: 8,
                        handler: () async {
                          widget.orderPreviewViewModel!.paymentCheckoutData.address = Addresses.fromJson(model.addresses[model.selectedAddressIndex].toJson());
                          GifLoaderDialogUtils.showMyDialog(context);
                          await widget.orderPreviewViewModel!.getInformationsByAddress(projectProvider.user!.patientIdentificationNo!);
                          if (widget.orderPreviewViewModel!.error == "") {
                            await widget.orderPreviewViewModel!.getShoppingCart();
                            GifLoaderDialogUtils.hideDialog(context);
                            model.saveSelectedAddressLocally(model.addresses[model.selectedAddressIndex]);
                            _navigateToPaymentOption(model);
                          } else {
                            GifLoaderDialogUtils.hideDialog(context);
                            AppToast.showErrorToast(message: widget.orderPreviewViewModel!.error);
                            return;
                          }
                        },
                      ),
                    ),
                  ],
                ),
              )
            : SizedBox(),
      ),
    );
  }

  _navigateToPaymentOption(model) {
    if (widget.isUpdate) {
      widget.orderPreviewViewModel!.paymentCheckoutData.address = Addresses.fromJson(model.addresses[model.selectedAddressIndex].toJson());
      widget.changeMainState!();
      Navigator.pop(context);

      return;
    }
    Navigator.push(
        context,
        FadePage(
            page: PaymentMethodSelectPage(
          model: widget.orderPreviewViewModel!,
        ))).then((result) => {
          setState(() {
            if (result != null) {
              var paymentOption = result;
              widget.orderPreviewViewModel!.paymentCheckoutData!.paymentOption = paymentOption;
            }
            // widget.changeMainState();
          })
        });
  }
}

class AddressItemWidget extends StatefulWidget {
  final PharmacyAddressesViewModel model;
  final AddressInfo address;
  final VoidCallback selectAddress;
  final bool isSelected;
  final Function(AddressInfo) onTabEditAddress;

  AddressItemWidget(this.model, this.address, this.selectAddress, this.isSelected, this.onTabEditAddress);

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

class _AddressItemWidgetState extends State<AddressItemWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 0),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    InkWell(
                      onTap: widget!.selectAddress!,
                      child: Container(
                        margin: EdgeInsets.only(left: 16, right: 16),
                        child: Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: Container(
                            decoration: new BoxDecoration(
                              color: !widget.isSelected ? Colors.white : Colors.green,
                              shape: BoxShape.circle,
                              border: Border.all(color: Colors.grey, style: BorderStyle.solid, width: 1.0),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(0.0),
                              child: Icon(
                                Icons.check,
                                color: widget.isSelected ? Colors.white : Colors.transparent,
                                size: 25,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Expanded(
                  child: Container(
                    child: Container(
                      margin: EdgeInsets.symmetric(vertical: 12, horizontal: 12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 0),
                            child: Texts(
                              "${widget.address.firstName} ${widget.address.lastName}",
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              color: Colors.black,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 4),
                            child: Texts(
                              "${widget.address.address1} ${widget.address.address2} ${widget.address.address2},, ${widget.address.city}, ${widget.address.country} ${widget.address.zipPostalCode}",
                              fontSize: 12,
                              fontWeight: FontWeight.normal,
                              color: Colors.grey.shade500,
                            ),
                          ),
                          Row(
                            children: [
                              Container(
                                margin: const EdgeInsets.only(right: 8),
                                child: Icon(
                                  Icons.phone,
                                  size: 20,
                                  color: Colors.black,
                                ),
                              ),
                              Texts(
                                "${widget.address.phoneNumber}",
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                                color: Colors.grey,
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            height: 25,
                            child: Row(
                              children: <Widget>[
                                BorderedButton(
                                  TranslationBase.of(context).edit,
                                  backgroundColor: Colors.transparent,
                                  hasBorder: true,
                                  borderColor: Colors.transparent,
                                  textColor: Color(0x990000FF),
                                  handler: () {
                                    widget.onTabEditAddress(widget.address);
                                  },
                                  icon: Icon(
                                    Icons.edit,
                                    size: 15,
                                    color: Color(0x990000FF),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 8),
                                  child: SizedBox(
                                    child: Container(
                                      width: 1,
                                      color: Colors.grey.shade400,
                                    ),
                                  ),
                                ),
                                BorderedButton(
                                  TranslationBase.of(context).delete,
                                  backgroundColor: Colors.transparent,
                                  hasBorder: true,
                                  borderColor: Colors.transparent,
                                  textColor: Color(0x99FF0000),
                                  handler: () {
                                    ConfirmDialog dialog = new ConfirmDialog(
                                        context: context,
                                        title: TranslationBase.of(context).deleteAddress,
                                        confirmMessage: "${widget.address.address1} ${widget.address.address2}",
                                        okText: TranslationBase.of(context).delete,
                                        cancelText: TranslationBase.of(context).cancel_nocaps,
                                        okFunction: () => {
                                              ConfirmDialog.closeAlertDialog(context),
                                              setState(() {
                                                widget.model.deleteAddresses(widget.address).then((_) {
                                                  AppToast.showSuccessToast(
                                                    message: TranslationBase.of(context).deletedAddress,
                                                  );
                                                  // widget.model.getAddressesList();
                                                });
                                              }),
                                            },
                                        cancelFunction: () => {});
                                    dialog.showAlertDialog(context);
                                  },
                                  icon: Icon(
                                    Icons.delete,
                                    size: 15,
                                    color: Color(0x99FF0000),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Divider(
              color: Colors.grey.shade200,
              height: 10,
              thickness: 10,
              indent: 0,
              endIndent: 0,
            ),
          ],
        ),
      ),
    );
  }
}
