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/theme/colors.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/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.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;
  final GlobalKey locationDropdownKey = GlobalKey();

  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);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).covidTest,
      isShowAppBar: true,
      imagesInfo: imagesInfo,
      description: TranslationBase.of(context).covidInfo,
      isShowDecPage: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      backgroundColor: CustomColors.appBackgroudGrey2Color,
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Container(
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(left: 14, right: 14),
                      child: Column(
                        children: [
                          Container(
                            alignment: projectViewModel.isArabic ? Alignment.centerRight : Alignment.centerLeft,
                            child: Text(TranslationBase.of(context).resultHeader, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0, color: Colors.black, letterSpacing: -1.14)),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 6.0),
                            child: Text(TranslationBase.of(context).covidInfo, style: TextStyle(fontSize: 14.0, color: Colors.black, letterSpacing: -0.56)),
                          ),
                          InkWell(
                            onTap: () {
                              // dropdownKey.currentState;
                              // openDropdown(clinicDropdownKey);
                            },
                            child: Container(
                              width: double.infinity,
                              decoration: containerRadius(Colors.white, 12),
                              margin: EdgeInsets.only(top: 12),
                              padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
                              child: Row(
                                children: [
                                  Flexible(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          TranslationBase.of(context).selectLocation,
                                          style: TextStyle(
                                            fontSize: 11,
                                            letterSpacing: -0.44,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                        Container(
                                          height: 20,
                                          child: DropdownButtonHideUnderline(
                                            child: DropdownButton<DriveThroughTestingCenterModel>(
                                              onTap: () {
                                                print("Clicked");
                                              },
                                              key: locationDropdownKey,
                                              hint: new Text(
                                                TranslationBase.of(context).selectAddress,
                                              ),
                                              value: selectedProject,
                                              iconSize: 0,
                                              isExpanded: true,
                                              style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black, fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins'),
                                              items: projectsList.map((DriveThroughTestingCenterModel item) {
                                                return new DropdownMenuItem<DriveThroughTestingCenterModel>(
                                                  value: item,
                                                  child: Row(
                                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                    children: [Text(item.projectName), getCovidTestTypeImage(item)],
                                                  ),
                                                );
                                              }).toList(),
                                              onChanged: (newValue) {
                                                setState(() {
                                                  selectedProject = newValue;
                                                  setProjectLocation(newValue);
                                                });
                                              },
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Icon(Icons.keyboard_arrow_down),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    mHeight(20),
                    isLocationSelected
                        ? Stack(
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 5.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"),
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  InkWell(
                                    onTap: () {
                                      getDirections();
                                    },
                                    child: Container(
                                      decoration: cardRadius(1000),
                                      margin: EdgeInsets.all(12),
                                      child: Padding(
                                        padding: const EdgeInsets.only(left: 12, right: 12, top: 6, bottom: 6),
                                        child: Row(
                                          children: [
                                            Padding(
                                              padding: const EdgeInsets.all(3.0),
                                              child: SvgPicture.asset(
                                                "assets/images/new/direction.svg",
                                                width: 13,
                                                height: 13,
                                              ),
                                            ),
                                            mWidth(6),
                                            Text(
                                              TranslationBase.of(context).getDirections,
                                              style: TextStyle(
                                                color: Colors.black,
                                                fontSize: 11,
                                                letterSpacing: -0.44,
                                                fontWeight: FontWeight.w600,
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          )
                        : SizedBox(
                            height: MediaQuery.of(context).size.height * 0.35,
                          ),
                    mHeight(12),
                  ],
                ),
              ),
            ),
          ),
          Card(
            elevation: 0,
            margin: EdgeInsets.zero,
            child: Container(
                width: double.infinity,
                padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 12),
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.width * 0.7,
                  height: 45.0,
                  child: RaisedButton(
                    color: CustomColors.accentColor,
                    textColor: Colors.white,
                    disabledTextColor: Colors.white,
                    disabledColor: CustomColors.accentColor,
                    elevation: 0,
                    onPressed: () {
                      next();
                    },
                    child: Text(
                      TranslationBase.of(context).next,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -0.44,
                      ),
                    ),
                  ),
                )),
          ),
        ],
      ),
    );
  }

  Widget getCovidTestTypeImage(DriveThroughTestingCenterModel item) {
    if (item.testTypeEnum == 1) {
      return Container(child: SvgPicture.asset("assets/images/new/DriveThru.svg", width: 20.0));
    }
    if (item.testTypeEnum == 2) {
      return Container(child: SvgPicture.asset("assets/images/new/WalkIn.svg", width: 10.0));
    }
    if (item.testTypeEnum == 3) {
      return Row(
        children: [
          Container(child: SvgPicture.asset("assets/images/new/WalkIn.svg", width: 10.0)),
          Container(padding: EdgeInsets.only(left: 5.0, right: 5.0), child: SvgPicture.asset("assets/images/new/DriveThru.svg", width: 20.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, selectedProject: selectedProject)));
    } 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;
    });
    getTestProcedures(context);
  }

  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, selectedProject.testTypeEnum, selectedProject.testProcedureEnum).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,
              selectedProject: selectedProject,
            )));
      } else {}
    }).catchError((err) {
      print(err);
    });
  }

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

    service.getCovidTestProceduresList(context, selectedProject.testTypeEnum, selectedProject.testProcedureEnum, selectedProject.projectID).then((res) {
      if (res['MessageStatus'] == 1) {
        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);
    });
  }
}
