import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/CovidDriveThru/CovidPaymentInfoResponse.dart';
import 'package:diplomaticquarterapp/models/CovidDriveThru/CovidTestProceduresResponse.dart';
import 'package:diplomaticquarterapp/models/CovidDriveThru/DriveThroughTestingCenterModel.dart';
import 'package:diplomaticquarterapp/pages/Covid-DriveThru/covid-payment-details.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/covid-drivethru/covid-drivethru.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:maps_launcher/maps_launcher.dart';
import 'package:provider/provider.dart';

import 'covid-dirvethru-questions.dart';

class CovidDrivethruLocation extends StatefulWidget {
  @override
  _CovidDrivethruLocationState createState() => _CovidDrivethruLocationState();
}

class _CovidDrivethruLocationState extends State<CovidDrivethruLocation> {
  String projectDropdownValue;
  List<DriveThroughTestingCenterModel> projectsList = [];
  List<CovidTestProceduresResponse> proceduresList = [];
  bool isLocationSelected = false;
  String projectLat = "";
  String projectLong = "";
  String projectName = "";
  String projectID = "";
  List<ImagesInfo> imagesInfo = List();

  DriveThroughTestingCenterModel selectedProject;

  ProjectViewModel projectViewModel;

  @override
  void initState() {
    imagesInfo.add(
      ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/covid/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/covid/ar/0.png'),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (projectViewModel.isLogin) {
        getProjectsList(context);
        getTestProcedures(context);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    imagesInfo.add(ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/covid/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/covid/ar/0.png'));
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).covidTest,
      isShowAppBar: true,
      imagesInfo: imagesInfo,
      description: TranslationBase.of(context).covidInfo,
      isShowDecPage: true,
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                alignment: projectViewModel.isArabic ? Alignment.centerRight : Alignment.centerLeft,
                child: Text(TranslationBase.of(context).resultHeader, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22.0, color: Colors.black)),
              ),
              Container(
                margin: EdgeInsets.only(top: 10.0),
                child: Text(TranslationBase.of(context).covidInfo, style: TextStyle(fontSize: 16.0, color: Colors.black)),
              ),
              Container(
                margin: EdgeInsets.only(top: 20.0),
                alignment: projectViewModel.isArabic ? Alignment.centerRight : Alignment.centerLeft,
                child: Text(TranslationBase.of(context).selectLocation, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0, letterSpacing: 0.8, color: Colors.grey[700])),
              ),
              Container(
                  height: 60.0,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(
                      color: Colors.grey[400],
                      width: 1.0,
                    ),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  padding: EdgeInsets.all(8.0),
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.only(top: 15.0),
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton<DriveThroughTestingCenterModel>(
                      hint: new Text(TranslationBase.of(context).selectAddress),
                      value: selectedProject,
                      items: projectsList.map((DriveThroughTestingCenterModel item) {
                        return new DropdownMenuItem<DriveThroughTestingCenterModel>(
                          value: item,
                          child: new Text(item.projectName),
                        );
                      }).toList(),
                      onChanged: (newValue) {
                        setState(() {
                          selectedProject = newValue;
                          setProjectLocation(newValue);
                        });
                      },
                    ),
                  )),
              isLocationSelected
                  ? Container(
                      margin: EdgeInsets.only(top: 15.0),
                      alignment: projectViewModel.isArabic ? Alignment.centerRight : Alignment.centerLeft,
                      child: Text(TranslationBase.of(context).selectLocation, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0, letterSpacing: 0.8, color: Colors.black)),
                    )
                  : Container(),
              isLocationSelected
                  ? Container(
                      margin: EdgeInsets.only(top: 5.0),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey[400], width: 1.0),
                      ),
                      child: Image.network("https://maps.googleapis.com/maps/api/staticmap?center=" +
                          this.projectLat +
                          "," +
                          this.projectLong +
                          "&zoom=15&size=800x400&maptype=roadmap&markers=color:red%7C" +
                          this.projectLat +
                          "," +
                          this.projectLong +
                          "&key=AIzaSyCyDbWUM9d_sBUGIE8PcuShzPaqO08NSC8"),
                    )
                  : SizedBox(
                      height: MediaQuery.of(context).size.height * 0.35,
                    ),
              Container(
                height: MediaQuery.of(context).size.height * 0.15,
                width: double.infinity,
                child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      child: ButtonTheme(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        minWidth: MediaQuery.of(context).size.width * 0.91,
                        height: 45.0,
                        child: RaisedButton(
                          color: new Color(0xFFc5272d),
                          textColor: Colors.white,
                          disabledTextColor: Colors.white,
                          disabledColor: Colors.red[300],
                          onPressed: () {
                            getDirections();
                          },
                          child: Text(TranslationBase.of(context).getDirections, style: TextStyle(fontSize: 18.0)),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Container(
                              margin: EdgeInsets.fromLTRB(10.0, 0.0, 5.0, 0.0),
                              child: ButtonTheme(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                                minWidth: MediaQuery.of(context).size.width * 0.7,
                                height: 45.0,
                                child: RaisedButton(
                                  color: new Color(0xFF60686b),
                                  textColor: Colors.white,
                                  disabledTextColor: Colors.white,
                                  disabledColor: Colors.grey[500],
                                  onPressed: () {
                                    back();
                                  },
                                  child: Text(TranslationBase.of(context).back, style: TextStyle(fontSize: 18.0)),
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: Container(
                              margin: EdgeInsets.fromLTRB(10.0, 0.0, 5.0, 0.0),
                              child: ButtonTheme(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                                minWidth: MediaQuery.of(context).size.width * 0.7,
                                height: 45.0,
                                child: RaisedButton(
                                  color: new Color(0xFF60686b),
                                  textColor: Colors.white,
                                  disabledTextColor: Colors.white,
                                  disabledColor: Colors.grey[500],
                                  onPressed: () {
                                    next();
                                  },
                                  child: Text(TranslationBase.of(context).next, style: TextStyle(fontSize: 18.0)),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  getDirections() {
    if (isLocationSelected) {
      MapsLauncher.launchCoordinates(double.parse(projectLat), double.parse(projectLong), this.projectName);
    } else {
      Utils.showErrorToast("Please select address from the dropdown menu to get directions");
    }
  }

  next() {
    if (isLocationSelected) {
      Navigator.push(context, FadePage(page: CovidDirveThruQuestions(projectId: projectID, proceduresList: proceduresList)));
    } else {
      Utils.showErrorToast("Please select address from the dropdown menu to continue");
    }
  }

  back() {
    Navigator.of(context).popAndPushNamed(HOME);
  }

  setProjectLocation(DriveThroughTestingCenterModel newValue) {
    setState(() {
      this.projectLat = newValue.latitude.toString();
      this.projectLong = newValue.longitude.toString();
      this.projectName = newValue.projectName;
      this.projectID = newValue.projectID.toString();
      isLocationSelected = true;
    });
  }

  getPaymentInfo(BuildContext context, String projectID) {
    CovidDriveThruService service = new CovidDriveThruService();
    CovidPaymentInfoResponse covidPaymentInfoResponse = new CovidPaymentInfoResponse();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getCovidPaymentInformation(context, int.parse(projectID), proceduresList[0].procedureID).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          covidPaymentInfoResponse = CovidPaymentInfoResponse.fromJson(res['COVID19_PatientShare']);
        });
        Navigator.push(
            context,
            FadePage(
                page: CovidPaymentDetails(
              covidPaymentInfoResponse: covidPaymentInfoResponse,
              projectID: int.parse(projectID),
              proceduresList: proceduresList,
            )));
      } else {}
    }).catchError((err) {
      print(err);
    });
  }

  getTestProcedures(BuildContext context) {
    CovidDriveThruService service = new CovidDriveThruService();
    GifLoaderDialogUtils.showMyDialog(context);

    CovidTestProceduresResponse covidTestProceduresResponse = new CovidTestProceduresResponse();

    service.getCovidTestProceduresList(context).then((res) {
      if (res['MessageStatus'] == 1) {
        print(res);
        setState(() {
          res['COVID19_TestProceduresList'].forEach((v) {
            proceduresList.add(new CovidTestProceduresResponse.fromJson(v));
          });
        });
        print(proceduresList.length);
        print(proceduresList[0].procedureName);
        GifLoaderDialogUtils.hideDialog(context);
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  getProjectsList(BuildContext context) {
    CovidDriveThruService service = new CovidDriveThruService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getCovidProjectsList(context).then((res) {
      projectsList.clear();
      if (res['MessageStatus'] == 1) {
        setState(() {
          res['List_COVID19_ProjectDriveThroughTestingCenter'].forEach((v) {
            projectsList.add(new DriveThroughTestingCenterModel.fromJson(v));
          });
        });
        GifLoaderDialogUtils.hideDialog(context);
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
