import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/CovidDriveThru/CovidPaymentInfoResponse.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';

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

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

  ProjectViewModel projectViewModel;

  @override
  void initState() {
    WidgetsBinding.instance
        .addPostFrameCallback((_) => getProjectsList(context));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).covidTest,
      isShowAppBar: true,
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
          child: Column(
            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<String>(
                      hint: new Text(TranslationBase.of(context).selectAddress),
                      value: projectDropdownValue,
                      items: projectsList.map((item) {
                        return new DropdownMenuItem<String>(
                          value: item.iD.toString(),
                          child: new Text(item.projectName),
                        );
                      }).toList(),
                      onChanged: (newValue) {
                        setState(() {
                          projectDropdownValue = 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"),
                    )
                  : Container(),
            ],
          ),
        ),
      ),
      bottomSheet: 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) {
      getPaymentInfo(context, projectID);
    } else {
      Utils.showErrorToast(
          "Please select address from the dropdown menu to continue");
    }
  }

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

  setProjectLocation(newValue) {
    print(newValue);
    setState(() {
      this.projectLat =
          projectsList[(int.parse(newValue) - 1)].latitude.toString();
      this.projectLong =
          projectsList[(int.parse(newValue) - 1)].longitude.toString();
      this.projectName = projectsList[(int.parse(newValue) - 1)].projectName;
      this.projectID =
          projectsList[(int.parse(newValue) - 1)].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))
        .then((res) {
          GifLoaderDialogUtils.hideDialog(context);
          if (res['MessageStatus'] == 1) {
            setState(() {
              covidPaymentInfoResponse = CovidPaymentInfoResponse.fromJson(
                  res['COVID19_PatientShare']);
              print(covidPaymentInfoResponse.procedureNameField);
            });
            Navigator.push(
                context,
                FadePage(
                    page: CovidPaymentDetails(
                      covidPaymentInfoResponse: covidPaymentInfoResponse,
                      projectID: int.parse(projectID),
                    )));
          } else {}
        })
        .catchError((err) {
          print(err);
        });
  }

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