import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:hmg_patient_app/core/viewModels/er/rrt-view-model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/rrt/RRTProcedureList.dart';
import 'package:hmg_patient_app/models/rrt/RRTRequestModel.dart';
import 'package:hmg_patient_app/models/rrt/service_price.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/ComprehensiveMedicalCheckup/Dialog/confirm_dialog.dart';
import 'package:hmg_patient_app/pages/ErService/rapid-response-team/rrt-main-screen.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/theme/colors.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/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.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/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';

class RRTPlaceOrderPage extends StatelessWidget {
  late TranslationBase localize;
  RRTViewModel? viewModel;
  AddressInfo selectedAddress;
  final ServicePrice servicePrice;
  final VidaProcedureList selectedProcedure;

  RRTPlaceOrderPage({required this.selectedAddress, required this.servicePrice, required this.selectedProcedure});

  TextEditingController noteController = TextEditingController(text: '');
  late BuildContext _context;

  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    _context = context;
    localize = TranslationBase.of(context);
    var lat = selectedAddress.latLong!.split(',').first;
    var lng = selectedAddress.latLong!.split(',').last;

    return BaseView<RRTViewModel>(
      onModelReady: (vm) => viewModel = vm,
      builder: (ctx, vm, wState) {
        return AppScaffold(
          appBarTitle: localize.rapidResponseTeam,
          isShowAppBar: true,
          showNewAppBarTitle: true,
          showNewAppBar: true,
          body: SingleChildScrollView(
            padding: EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  localize.selectedLocation,
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                selectedAddressField(),
                AspectRatio(
                  aspectRatio: 3 / 1,
                  child: ClipRRect(
                    clipBehavior: Clip.hardEdge,
                    borderRadius: BorderRadius.circular(10),
                    child: Image.network(
                      "https://maps.googleapis.com/maps/api/staticmap?center=$lat,$lng &zoom=17&size=800x600&maptype=roadmap&markers=color:red%7C$lat,$lng&key=AIzaSyCyDbWUM9d_sBUGIE8PcuShzPaqO08NSC8",
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  height: 85,
                  margin: EdgeInsets.symmetric(vertical: 5),
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [BoxShadow(blurRadius: 5, spreadRadius: 2, offset: Offset(2, 2), color: Colors.grey.withOpacity(0.25))]),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        localize.patientShareWithTax,
                        style: TextStyle(fontSize: 13),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Row(
                        children: [
                          projectViewModel!.isArabic ? Container() : SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 18, height: 18),
                          mWidth(6),
                          Text(
                            "${selectedProcedure.patientShareWithTax ?? '- - -'}",
                            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          mWidth(6),
                          projectViewModel!.isArabic ? SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 18, height: 18) : Container(),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 70,
                  margin: EdgeInsets.symmetric(vertical: 5),
                  padding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [BoxShadow(blurRadius: 5, spreadRadius: 2, offset: Offset(2, 2), color: Colors.grey.withOpacity(0.25))]),
                  child: TextField(
                      controller: noteController,
                      style: TextStyle(fontSize: 18.0),
                      decoration: InputDecoration(
                        filled: true,
                        fillColor: Colors.white,
                        labelText: localize.notes,
                        contentPadding: const EdgeInsets.only(left: 14.0, bottom: 8.0, top: 8.0),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.white),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.white),
                          borderRadius: BorderRadius.circular(10),
                        ),
                      )),
                ),
              ],
            ),
          ),
          bottomSheet: submitButton(context),
        );
      },
    );
  }

  Widget selectedAddressField() {
    var address = "${selectedAddress.address1 ?? ''} ${selectedAddress.address2 ?? ''}";
    return selectedAddress.address1 != null
        ? Container(
            margin: EdgeInsets.symmetric(vertical: 10),
            child: MaterialButton(
              height: 50,
              color: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
              onPressed: () {},
              child: Row(
                children: [
                  Expanded(child: Text(address, style: TextStyle(color: Colors.black87, fontSize: 12, letterSpacing: 1))),
                  Icon(
                    Icons.location_on_rounded,
                    size: 30,
                    color: Colors.black,
                  )
                ],
              ),
            ),
          )
        : SizedBox();
  }

  Widget submitButton(BuildContext context) {
    return Container(
      color: Theme.of(context).scaffoldBackgroundColor,
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: DefaultButton(
          localize.submit,
          () => placeOrder(),
          color: CustomColors.green,
        ),
      ),
    );
  }

  placeOrder() async {
    if (selectedAddress != null && selectedAddress.latLong != null && selectedAddress.latLong!.isNotEmpty && selectedAddress.latLong!.split(',').length > 1) {
      GifLoaderDialogUtils.showMyDialog(_context);

      RRTRequestModel rrtRequestModel = new RRTRequestModel();
      Procedures procedures = new Procedures();
      rrtRequestModel.procedures = [];

      Map<String, dynamic> params = {};
      var cordinates = selectedAddress.latLong!.split(',');
      var latlng = LatLng(double.parse(cordinates.first), double.parse(cordinates.last));

      procedures.serviceID = selectedProcedure.procedureID;

      rrtRequestModel.latitude = latlng.latitude;
      rrtRequestModel.longitude = latlng.longitude;
      rrtRequestModel.additionalDetails = noteController.text;
      rrtRequestModel.nationality = projectViewModel.user!.nationalityID;
      rrtRequestModel.paymentAmount = selectedProcedure.patientShareWithTax;
      rrtRequestModel.nearestProjectId = 0;
      rrtRequestModel.patientId = projectViewModel.user!.patientID;
      rrtRequestModel.patientOutSa = projectViewModel.user!.outSA;
      rrtRequestModel.procedures!.add(procedures);

      // params['latitude'] = latlng.latitude;
      // params['longitude'] = latlng.longitude;
      // params['additionalDetails'] = noteController.text;
      // params['nationality'] = projectViewModel.user.nationalityID;
      // params['paymentAmount'] = selectedProcedure.patientShareWithTax;
      // params['procedureId'] = selectedProcedure.procedureID;

      await viewModel!.createOrderRC(rrtRequestModel.toJson());

      GifLoaderDialogUtils.hideDialog(_context);

      if (viewModel!.createdRequestNo != null) {
        showCMCConfirmDialog(
          _context,
          viewModel!.createdRequestNo.toString(),
          onClick: () {
            Navigator.pop(_context);
            Navigator.pop(_context);
            gotoRRTRoot();
          },
        );
      }

      // if (requestId != null) {
      //   AlertDialogBox(
      //       context: _context,
      //       title: '',
      //       confirmMessage: localize.rrtOrderSuccessMessage,
      //       okText: localize.ok,
      //       okFunction: () {
      //         AlertDialogBox.closeAlertDialog(_context);
      //         gotoRRTRoot();
      //       }).showAlertDialog(_context);
      // }
    } else {
      AppToast.showErrorToast(message: 'Invalid location selected');
    }
  }

  gotoRRTRoot() async {
    viewModel!.setState(ViewState.Busy);
    await viewModel!.getAllOrdersRC();
    viewModel!.setState(ViewState.Idle);
    Navigator.popUntil(_context, (route) => Utils.route(route, equalsTo: RRTMainScreen));
    Navigator.push(_context, FadePage(page: RRTMainScreen()));
  }
}
