import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/viewModels/er/rrt-view-model.dart';
import 'package:diplomaticquarterapp/models/rrt/service_price.dart';
import 'package:diplomaticquarterapp/pages/ErService/ErOptions.dart';
import 'package:diplomaticquarterapp/pages/ErService/rapid-response-team/rrt-main-screen.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class RRTPlaceOrderPage extends StatelessWidget{
  TranslationBase localize;
  RRTViewModel viewModel;
  Addresses selectedAddress;
  final ServicePrice servicePrice;

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

  TextEditingController noteController = TextEditingController(text: '');
  BuildContext _context;
  @override
  Widget build(BuildContext 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,
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Expanded(
                  child: 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=16&size=800x400&maptype=roadmap&markers=color:red%7C$lat,$lng&key=AIzaSyCyDbWUM9d_sBUGIE8PcuShzPaqO08NSC8",
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),

                        SizedBox(height: 10,),

                        Container(
                          height: 70,
                          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.totalAmountPayable, style: TextStyle(fontSize: 13),),
                              SizedBox(height: 5,),
                              Text("${servicePrice.totalPrice ?? '- - -'} ${localize.sar}" , style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
                            ],
                          ),
                        ),

                        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),
                                ),
                              )
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                submitButton(context)
              ],
            )
        );
      },
    );
  }


  Widget selectedAddressField(){
    var address = "${selectedAddress.address1 ?? ''} ${selectedAddress.address2 ?? ''}";
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Expanded(
        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: 15, letterSpacing: 1))),
              Icon(Icons.location_on_rounded, size: 30, color: Colors.black,)
            ],
          ),
        ),
      ),
    );
  }


  Widget submitButton(BuildContext context){
    return Padding(
      padding: const EdgeInsets.all(15),
      child: MaterialButton(
        height: 50,
        color: Theme.of(context).appBarTheme.color,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        onPressed: () => placeOrder(),
        child: Text(localize.submit, style: TextStyle(color: Colors.white, fontSize: 15, letterSpacing: 1),),
      ),
    );
  }

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

      Map<String, dynamic> params = {};
      var cordinates = selectedAddress.latLong.split(',');
      var latlng = LatLng(double.parse(cordinates.first), double.parse(cordinates.last));
      params['Latitude'] = latlng.latitude;
      params['Longitude'] = latlng.longitude;
      params['Notes'] = noteController.text;
      var requestId = await viewModel.createOrder(params);

      GifLoaderDialogUtils.hideDialog(_context);

      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(){
    Navigator.popUntil(_context, (route) => Utils.route(route, equalsTo: ErOptions));
  }
}