import 'package:bottom_bar_matu/utils/app_utils.dart';
import 'package:echo_app/models/constant-operator.dart';
import 'package:echo_app/widgets/points_dialog.widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_paytabs_bridge/BaseBillingShippingInfo.dart';
import 'package:flutter_paytabs_bridge/IOSThemeConfiguration.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkApms.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkConfigurationDetails.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkLocale.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkTokeniseType.dart';
import 'package:flutter_paytabs_bridge/flutter_paytabs_bridge.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';

import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:place_picker/entities/location_result.dart';
import 'package:place_picker/widgets/place_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../enums/alert_types.dart';
import '../models/constant-storage.dart';
import '../screens/map/MapScreen.dart';
import '../shared/core.session.dart';
import '../theme/variables.dart';
import 'Selections/MultiCheckBox.dart';
import 'alert.widget.dart';
import 'general_text_form_field.widget.dart';
import 'newPlacePicker.dart';

class checkOutBottom extends StatelessWidget {
  final double nettotal;
  final Function Checkout;
  final BuildContext context;
  LatLng location;
  static String locationDesc = '';
  static LatLng selectedLocation = LatLng(0.0, 0.0);
  int PaymentType = 0;
  static TextEditingController passController = new TextEditingController();
  static double pointValue = 0;

  checkOutBottom(this.nettotal, this.Checkout, this.context, this.location) {
    if (selectedLocation.latitude > 0.0) location = selectedLocation;
    this.updatePointValue(CoreSession.usedPoints);
  }

  Future<void> getHomeData(context) async {
    locationDesc = await CoreSession.getLocationName();
    (context as Element).markNeedsBuild();
  }

  void showPlacePicker(customLocation) async {
    try {
      LocationResult? result =
          await Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => newPlacePicker(
                    "AIzaSyCz8GLpL9iluRZbeSwwTglQm7P9JNR0QQI",
                    displayLocation: customLocation,
                    defaultLocation: customLocation,
                  )));
      if (result == null) {
        (context as Element).markNeedsBuild();
        return;
      }
      locationDesc =
          result!.name.toString() + ', ' + result.locality.toString();
      selectedLocation = result.latLng!;
      (context as Element).markNeedsBuild();
      if (selectedLocation.latitude != 0.0) location = selectedLocation;
    } catch (e) {
      // No specified type, handles all
      print('Something really unknown: $e');
    }
  }

  updatePointValue(value) {
    CoreSession.usedPoints = value;
    if (value != "") {
      String pointsConversionFactor = CoreSession
                  .currentOperator[ConstantOperator.pointsConversionFactor] !=
              null
          ? CoreSession.currentOperator[ConstantOperator.pointsConversionFactor]
              .toString()
          : "0";
      pointValue = double.parse(value) * double.parse(pointsConversionFactor);
    } else {
      pointValue = 0;
    }
    CoreSession.pointValue = pointValue;
    (context as Element).markNeedsBuild();
  }

  @override
  Widget build(BuildContext context) {
    var size;
    List<String> options = [
      'cashOnDelivery'.tr,
      'credit-Card'.tr,
    ];
    size = MediaQuery.of(context).size.width * 0.9;
    if (locationDesc.isEmpty) getHomeData(context);
    var constPadding = EdgeInsets.fromLTRB(10, 0, 10, 0);
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              children: [
                Expanded(
                  flex: 5,
                  child: Text(
                    'checkout'.tr,
                    style: TextStyle(
                      fontSize: Variables.headline1FontSize,
                    ),
                  ),
                ),
                Spacer(),
                Expanded(
                  flex: 1,
                  child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Icon(Icons.close)),
                ),
              ],
            ),
          ),
          Divider(
            color: Colors.grey,
          ),
          Padding(
            padding:
                const EdgeInsets.symmetric(vertical: 20.0, horizontal: 15.0),
            child: Container(
              width: size,
              child: Column(
                children: [
                  InkWell(
                    onTap: () async {
                      var pos;
                      if (location.latitude == 0.0 &&
                          location.longitude == 0.0) {
                        var pos = await Geolocator.getCurrentPosition(
                            desiredAccuracy: LocationAccuracy.best);
                        location = LatLng(pos.latitude, pos.longitude);
                      }
                      showPlacePicker(location);
                    },
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            'location'.tr,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: Variables.headline2FontSize,
                                color: Colors.grey),
                          ),
                        ),
                        Expanded(
                          flex: 2,
                          child: Row(
                            children: [
                              SizedBox(
                                width: 190,
                                child: Text(
                                  locationDesc,
                                  style: TextStyle(
                                      fontSize: Variables.headline2FontSize,
                                      color: Colors.black),
                                ),
                              ),
                              Spacer(),
                              IconButton(
                                icon: Icon(Icons.arrow_forward_ios),
                                onPressed: () {},
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Divider(
                      color: Colors.grey,
                    ),
                  ),
                  InkWell(
                    onTap: () async {
                      var pos;
                      if (location.latitude == 0.0 &&
                          location.longitude == 0.0) {
                        var pos = await Geolocator.getCurrentPosition(
                            desiredAccuracy: LocationAccuracy.best);
                        location = LatLng(pos.latitude, pos.longitude);
                      }

                      MultipleValueSelection multi = MultipleValueSelection();
                      multi.showMultiRadioButtonDialog(context, (option) {
                        PaymentType = option;
                        (context as Element).markNeedsBuild();

                        if (option == 1) {}
                      }, options, PaymentType, 'payment-type');
                    },
                    child: Row(
                      children: [
                        Text(
                          'payment'.tr,
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.grey),
                        ),
                        Spacer(),
                        Row(
                          children: [
                            // Image.asset("assets/imgs/creditcard.png",width: 32 , height: 32,),
                            Text(
                              options[PaymentType],
                              style: TextStyle(
                                  fontSize: Variables.headline2FontSize,
                                  color: Colors.grey),
                            ),
                            IconButton(
                              icon: Icon(Icons.arrow_forward_ios),
                              onPressed: null,
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Divider(
                      color: Colors.grey,
                    ),
                  ),
                  // Row(
                  //   children: [
                  //     Expanded(
                  //       flex:5,
                  //       child: Padding(
                  //         padding: const EdgeInsets.all(4.0),
                  //         child: GeneralTextFormFieldWidget(
                  //             "insertPromo".tr,
                  //             passController,
                  //             false,
                  //             '',
                  //             true,
                  //             false,
                  //             null,
                  //             null,
                  //             null,
                  //             constPadding,
                  //             null,
                  //             1,
                  //             true,
                  //             false,
                  //             true,
                  //             12),
                  //       ),
                  //     ),
                  //     Expanded(
                  //       flex:2,
                  //       child: Container(
                  //         height: 40,
                  //         child: ElevatedButton(
                  //           onPressed: () {
                  //             Fluttertoast.showToast(
                  //                 msg: "error-promo".tr,
                  //                 toastLength: Toast.LENGTH_SHORT,
                  //                 gravity: ToastGravity.BOTTOM,
                  //                 timeInSecForIosWeb: 1,
                  //                 backgroundColor: Colors.red,
                  //                 textColor: Colors.white,
                  //                 fontSize: 16.0
                  //             );
                  //           },
                  //           child: Row(
                  //             children: [
                  //               Spacer(),
                  //               Text("apply".tr),
                  //               Spacer()
                  //             ],
                  //           ),
                  //           style: ElevatedButton.styleFrom(
                  //             backgroundColor: Variables.color_primary,
                  //             shape: RoundedRectangleBorder(
                  //               borderRadius: BorderRadius.circular(5),
                  //             ),
                  //           ),
                  //         ),
                  //       ),
                  //     ),
                  //   ],
                  // ),
                  // Padding(
                  //   padding: const EdgeInsets.all(8.0),
                  //   child: Divider(color: Colors.grey,),
                  // ),
                  if (CoreSession.currentOperator[ConstantOperator.pointsBalance] != null && CoreSession.currentOperator[
                              ConstantOperator.pointsBalance].toString().isNotNullOrEmpty() &&
                      double.parse(CoreSession.currentOperator[ConstantOperator.pointsBalance].toString()) > 0)
                    InkWell(
                      onTap: () async {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              // Return an AlertDialog widget
                              return PointsDialogWidget(
                                  CoreSession.usedPoints, updatePointValue, this.nettotal);
                            });
                      },
                      child: Row(
                        children: [
                          Text(
                            'Points'.tr,
                            style: TextStyle(
                                fontSize: Variables.headline2FontSize,
                                color: Colors.grey),
                          ),
                          Spacer(),
                          Row(
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  // First text
                                  Text(
                                    CoreSession.usedPoints != ""
                                        ? CoreSession.usedPoints +
                                            " " +
                                            "Points".tr
                                        : "Insert_Points".tr,
                                    style: TextStyle(
                                        fontSize: Variables.headline2FontSize,
                                        color: Colors.grey),
                                  ),
                                  // Second text
                                  if (CoreSession.usedPoints != "" &&
                                      double.parse(CoreSession.usedPoints) > 0)
                                    Padding(
                                      padding: const EdgeInsets.all(5.0),
                                      child: Text(
                                        pointValue
                                                .toStringAsFixed(
                                                    CoreSession.numberOfDigits)
                                                .toString() +
                                            " " +
                                            CoreSession.currentOperator[
                                                ConstantOperator.currencyCode],
                                        style: TextStyle(
                                          fontSize: Variables.headline2FontSize,
                                          color: Colors.red,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ],
                          ),
                          IconButton(
                              icon: Icon(Icons.arrow_forward_ios,
                                  color: Colors.grey),
                              onPressed: null),
                        ],
                      ),
                    ),
                 if (CoreSession.currentOperator[ConstantOperator.pointsBalance] != null && CoreSession.currentOperator[
                              ConstantOperator.pointsBalance].toString().isNotNullOrEmpty() &&
                      double.parse(CoreSession.currentOperator[ConstantOperator.pointsBalance].toString()) > 0)
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Divider(
                        color: Colors.grey,
                      ),
                    ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          'net-total'.tr,
                          style: TextStyle(
                              fontSize: Variables.headline2FontSize,
                              color: Colors.grey),
                        ),
                      ),
                      Spacer(),
                      Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              if (CoreSession.usedPoints != "" &&
                                  pointValue > 0)
                                Text(
                                  nettotal
                                          .toStringAsFixed(
                                              CoreSession.numberOfDigits)
                                          .toString() +
                                      " " +
                                      CoreSession.currentOperator[
                                          ConstantOperator.currencyCode],
                                  style: TextStyle(
                                      decoration: TextDecoration.lineThrough),
                                ),
                              Text((nettotal - pointValue)
                                      .toStringAsFixed(
                                          CoreSession.numberOfDigits)
                                      .toString() +
                                  " " +
                                  CoreSession.currentOperator[
                                      ConstantOperator.currencyCode]),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Divider(
                      color: Colors.grey,
                    ),
                  ),

                  Container(
                    width: size,
                    height: 50,
                    child: ElevatedButton(
                      onPressed: () async {
                        if (pointValue > nettotal) {
                          CoreSession.showToast('Invalid_Points');
                          return;
                        }
                        SharedPreferences prefs =
                            await SharedPreferences.getInstance();
                        prefs.setString(
                            ConstantStorage.deliveryLocation,
                            location.latitude.toString() +
                                ',' +
                                location.longitude.toString());

                        if (PaymentType == 0)
                          prefs.setInt(ConstantStorage.paymentType, 1);
                        else
                          prefs.setInt(ConstantStorage.paymentType, 9);
                        this.Checkout();
                        Navigator.pop(context);
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text("placeOrder".tr),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Variables.color_primary,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
