import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/GetCMCAllOrdersResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/cmc_insert_pres_order_request_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/HomeHealthCare/get_order_detail_by_order_iD_response_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/HomeHealthCare/update_pres_oreder_request_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/cmc_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/ComprehensiveMedicalCheckup/Dialog/confirm_cancel_order_dialog.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.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/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/ConfirmWithMessageDialog.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';

import 'new_cmc_step_one_page.dart';

class NewCMCPage extends StatefulWidget {
  NewCMCPage({this.model});

  final CMCViewModel model;

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

class _NewCMCPageState extends State<NewCMCPage> with TickerProviderStateMixin {
  PageController _controller;
  int _currentIndex = 1;

  double _latitude;
  double _longitude;

  CMCInsertPresOrderRequestModel cMCInsertPresOrderRequestModel;

  BuildContext _context;

  @override
  void initState() {
    super.initState();
    PatientERCMCInsertServicesList patientERCMCInsertServicesList;
    if (widget.model.cmcAllServicesList.length > 0) {
      patientERCMCInsertServicesList = new PatientERCMCInsertServicesList(
          price: widget.model.cmcAllServicesList[0].price,
          serviceID: widget.model.cmcAllServicesList[0].serviceID.toString(),
          selectedServiceName: widget.model.cmcAllServicesList[0].text,
          selectedServiceNameAR: widget.model.cmcAllServicesList[0].textN,
          recordID: 1,
          totalPrice: widget.model.cmcAllServicesList[0].priceTotal,
          vAT: widget.model.cmcAllServicesList[0].priceVAT);
      cMCInsertPresOrderRequestModel = new CMCInsertPresOrderRequestModel(patientERCMCInsertServicesList: [patientERCMCInsertServicesList]);
    }

    cMCInsertPresOrderRequestModel = new CMCInsertPresOrderRequestModel(patientERCMCInsertServicesList: patientERCMCInsertServicesList != null ? [patientERCMCInsertServicesList] : []);

    _controller = new PageController();

    _getCurrentLocation();
  }

  _getCurrentLocation() async {
    await Geolocator.getLastKnownPosition().then((value) {
      _latitude = value.latitude;
      _longitude = value.longitude;
    }).catchError((e) {
      _longitude = 0;
      _latitude = 0;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  changePageViewIndex(pageIndex) {
    _controller.jumpToPage(pageIndex);
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    ProjectViewModel projectViewModel = Provider.of(context);

    void showConfirmMessage(CMCViewModel model, GetCMCAllOrdersResponseModel order) {
      showDialog(
          context: context,
          builder: (cxt) => ConfirmWithMessageDialog(
            message: TranslationBase.of(context).cancelOrderMsg,
            onTap: () async {
              UpdatePresOrderRequestModel updatePresOrderRequestModel = UpdatePresOrderRequestModel(presOrderID: order.iD, rejectionReason: "", presOrderStatus: 4, editedBy: 3);
              Future.delayed(new Duration(milliseconds: 300)).then((value) async {
                GifLoaderDialogUtils.showMyDialog(_context);
                await model.updateCmcPresOrder(updatePresOrderRequestModel);
                if (model.state == ViewState.ErrorLocal) {
                  Utils.showErrorToast(model.error);
                  GifLoaderDialogUtils.hideDialog(_context);
                } else {
                  AppToast.showSuccessToast(message: TranslationBase.of(context).processDoneSuccessfully);
                  await model.getCmcAllPresOrders();
                  GifLoaderDialogUtils.hideDialog(_context);
                }
              });
            },
          ));
    }

    int status = widget.model.pendingOrder != null ? widget.model.pendingOrder.statusId : 0;
    String _statusDisp = widget.model.pendingOrder != null ? widget.model.pendingOrder.statusText : "";
    Color _color;
    if (status == 1) {
      //pending
      _color = Color(0xffCC9B14);
    } else if (status == 2) {
      //processing
      _color = Color(0xff2E303A);
    } else if (status == 3) {
      //completed
      _color = Color(0xff359846);
    } else if (status == 4 || status == 6 || status == 7) {
      //cancel // Rejected
      _color = Color(0xffD02127);
    }

    return Scaffold(
      body: SafeArea(
        child: Container(
          child: widget.model.pendingOrder != null
              ? Column(
                  children: [
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 12, right: 12, top: 12),
                      child: Container(
                        decoration: cardRadius(12),
                        margin: EdgeInsets.zero,
                        clipBehavior: Clip.antiAlias,
                        child: Container(
                          //  decoration: containerColorRadiusLeft(Colors.white, 12),
                          margin: EdgeInsets.only(left: projectViewModel.isArabic ? 0 : 6, right: projectViewModel.isArabic ? 6 : 0),
                          padding: EdgeInsets.symmetric(vertical: 14, horizontal: 12),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(color: Colors.white, width: 1),
                            borderRadius: BorderRadius.only(
                              bottomRight: projectViewModel.isArabic ? Radius.circular(0) : Radius.circular(10.0),
                              topRight: projectViewModel.isArabic ? Radius.circular(0) : Radius.circular(10.0),
                              bottomLeft: projectViewModel.isArabic ? Radius.circular(10.0) : Radius.circular(0),
                              topLeft: projectViewModel.isArabic ? Radius.circular(10.0) : Radius.circular(0),
                            ),
                          ),
                          // clipBehavior: Clip.antiAlias,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      _statusDisp,
                                      style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: _color, letterSpacing: -0.4, height: 16 / 10),
                                    ),
                                    SizedBox(height: 6),
                                    Text(
                                      '${TranslationBase.of(context).requestID}: ${widget.model.pendingOrder.iD}',
                                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64, height: 25 / 16),
                                    ),
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          TranslationBase.of(context).hospital + ": ",
                                          style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff575757), letterSpacing: -0.4, height: 16 / 10),
                                        ),
                                        Expanded(
                                          child: Text(
                                            // !projectViewModel.isArabic ? order.nearestProjectDescription.trim().toString() : order.nearestProjectDescriptionN.toString(),
                                            widget.model.pendingOrder.projectName.trim().toString(),
                                            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.56),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          TranslationBase.of(context).serviceName + ": ",
                                          style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff575757), letterSpacing: -0.4, height: 16 / 10),
                                        ),
                                        Expanded(
                                          child: Text(
                                            widget.model.pendingOrder.serviceText.trim().toString(),
                                            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.56),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    DateUtil.getDayMonthYearDateFormatted(DateTime.tryParse(widget.model.pendingOrder.created)),
                                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.4, height: 16 / 10),
                                  ),
                                  SizedBox(height: 12),
                                  if (widget.model.pendingOrder.statusId == 1 || widget.model.pendingOrder.statusId == 2)
                                    InkWell(
                                      onTap: () {
                                        showConfirmMessage(widget.model, widget.model.pendingOrder);
                                      },
                                      child: Container(
                                        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 14),
                                        decoration: BoxDecoration(
                                          color: Color(0xffD02127),
                                          border: Border.all(color: Colors.white, width: 1),
                                          borderRadius: BorderRadius.circular(10),
                                        ),
                                        child: Text(
                                          TranslationBase.of(context).cancel_nocaps,
                                          style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white, letterSpacing: -0.4),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                )
              : Container(
                  color: Colors.red,
                  child: NewCMCStepOnePage(
                    changePageViewIndex: changePageViewIndex,
                    cMCInsertPresOrderRequestModel: cMCInsertPresOrderRequestModel,
                    model: widget.model,
                    latitude: _latitude,
                    longitude: _longitude,
                  ),
                ),
        ),
      ),
    );
  }
}
