import 'dart:convert';

import 'package:diplomaticquarterapp/config/shared_pref_kay.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/medical/labs/passport_update_page.dart';
import 'package:diplomaticquarterapp/services/covid-drivethru/covid-drivethru.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.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_new.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'covid-payment-details.dart';

class CovidDirveThruQuestions extends StatefulWidget {
  final String projectId;
  final List<CovidTestProceduresResponse> proceduresList;
  DriveThroughTestingCenterModel selectedProject;

  CovidDirveThruQuestions({@required this.projectId, @required this.proceduresList, @required this.selectedProject});

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

class CovidDirveThruQuestionsState extends State<CovidDirveThruQuestions> {
  List qa;

  @override
  void initState() {
    super.initState();
    qa = getQuestionsFromJson();
  }

  TranslationBase localize;
  ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    localize = TranslationBase.of(context);
    var isArabic = localize.isArabic();
    projectViewModel = Provider.of(context);
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).covidTest,
        isShowAppBar: true,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        backgroundColor: CustomColors.appBackgroudGrey2Color,
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: double.infinity,
                        child: Container(
                          decoration: cardRadius(12),
                          margin: EdgeInsets.zero,
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  TranslationBase.of(context).covidBookAppo,
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                    letterSpacing: -0.64,
                                  ),
                                ),
                                mHeight(6),
                                Row(
                                  children: [
                                    Text(
                                      TranslationBase.of(context).patientName + ":",
                                      style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 10,
                                        letterSpacing: -0.6,
                                        color: CustomColors.grey,
                                      ),
                                    ),
                                    mWidth(3),
                                    Text(
                                      projectViewModel.user.firstName + " " + projectViewModel.user.lastName,
                                      style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 12,
                                        letterSpacing: -0.48,
                                      ),
                                    ),
                                  ],
                                ),
                                Row(
                                  children: [
                                    Text(
                                      TranslationBase.of(context).nationalIdNumber + ":",
                                      style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 10,
                                        letterSpacing: -0.6,
                                        color: CustomColors.grey,
                                      ),
                                    ),
                                    mWidth(3),
                                    Text(
                                      projectViewModel.user.patientIdentificationNo,
                                      style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 12,
                                        letterSpacing: -0.48,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      mHeight(12),
                      Text(
                        TranslationBase.of(context).covidQuestionnaire,
                        style: TextStyle(
                          fontSize: 16,
                          letterSpacing: -0.64,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      mHeight(12),
                      ListView.separated(
                        itemCount: qa.length,
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemBuilder: (ctx, idx) {
                          var obj = qa[idx];
                          var qtext = isArabic ? obj["questionAR"] : obj["questionEN"];

                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 10),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  qtext,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      child: Row(
                                        children: [
                                          Radio<int>(
                                              value: 1,
                                              groupValue: obj["ans"],
                                              onChanged: (newValue) {
                                                setState(() {
                                                  obj["ans"] = newValue;
                                                  checkAllChecked();
                                                });
                                              }),
                                          Text(
                                            localize.yes,
                                            style: TextStyle(
                                              fontSize: 12,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    Expanded(
                                      child: Row(
                                        children: [
                                          Radio<int>(
                                              value: 0,
                                              groupValue: obj["ans"],
                                              onChanged: (newValue) {
                                                setState(() {
                                                  obj["ans"] = newValue;
                                                  checkAllChecked();
                                                });
                                              }),
                                          Text(
                                            localize.no,
                                            style: TextStyle(
                                              fontSize: 12,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          );
                        },
                        separatorBuilder: (ctx, idx) => Container(),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Card(
              margin: EdgeInsets.zero,
              elevation: 0,
              child: Container(
                padding: EdgeInsets.all(12),
                child: FractionallySizedBox(
                  widthFactor: 1,
                  child: MaterialButton(
                    height: 50,
                    elevation: 0,
                    color: all2 ? CustomColors.accentColor : CustomColors.grey,
                    disabledColor: Theme.of(context).appBarTheme.color.withOpacity(0.25),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    child: Text(
                      localize.next,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -0.44,
                        color: Colors.white,
                      ),
                    ),
                    onPressed: next,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  bool all2 = false;

  checkAllChecked() {
    all2 = true;
    qa.forEach((element) {
      if (element["ans"] == 2 || element["ans"] == null) {
        all2 = false;
      }
    });
  }

  next() async {
    var sharedPref = new AppSharedPreferences();
    bool all = true;
    qa.forEach((element) {
      all = all && (element["ans"] == 1 || element["ans"] == 0);
    });
    if (all) if (qa[0]["ans"] == 1) {
      sharedPref.setObject(COVID_QA_LIST, qa);
      openPassportUpdatePage();
    } else {
      sharedPref.setObject(COVID_QA_LIST, qa);
      getPaymentInfo(context, widget.projectId);
    }
    else
      AppToast.showErrorToast(message: localize.pleaseSelectAllQuestionToContinue);
  }

  openPassportUpdatePage() {
    Navigator.push(context, FadePage(page: PassportUpdatePage())).then((value) {
      print(value);
      if (value != null && value == true) {
        getPaymentInfo(context, widget.projectId);
      }
    });
  }

  List getQuestionsFromJson() {
    var questionsJson = """
  [{ "id": 1, "questionEN": "Is the test intended for travel?", "questionAR": "هل تجري التحليل بغرض السفر؟", "ans": 2 }, { "id": 2, "questionEN": "Coming from outside KSA within last 2 weeks?", "questionAR": "هل قدمت من خارج المملكة خلال الأسبوعين الماضيين؟", "ans": 2 }, { "id": 3, "questionEN": "Do you currently have fever?", "questionAR": "هل تعاني حاليا من حرارة؟", "ans": 2 }, { "id": 4, "questionEN": "Did you have fever in last 2 weeks?", "questionAR": "هل عانيت من حرارة في الأسبوعين الماضيين؟", "ans": 2 }, { "id": 5, "questionEN": "Do you have a sore throat?", "questionAR": "هل لديك التهاب في الحلق؟", "ans": 2 }, { "id": 6, "questionEN": "Do you have a runny nose?", "questionAR": "هل لديك سيلان بالأنف؟" }, { "id": 7, "questionEN": "Do you have a cough?", "questionAR": "هل لديك سعال؟", "ans": 2 }, { "id": 8, "questionEN": "Do you have shortness of breath?", "questionAR": "هل تعاني من ضيق في التنفس؟", "ans": 2 }, { "id": 9, "questionEN": "Do you have nausea?", "questionAR": "هل تعاني من غثيان؟", "ans": 2 }, { "id": 10, "questionEN": "Do you have vomiting?", "questionAR": "هل تعاني من القيء؟", "ans": 2 }, { "id": 11, "questionEN": "Do you have a headache?", "questionAR": "هل تعاني من صداع في الرأس؟", "ans": 2 }, { "id": 12, "questionEN": "Do you have muscle pain?", "questionAR": "هل تعانين من آلام عضلية؟", "ans": 2 }, { "id": 13, "questionEN": "Do you have joint pain?", "questionAR": "هل تعاني من آلام المفاصل؟", "ans": 2 }, { "id": 14, "questionEN": "Do you have diarrhea?", "questionAR": "هل لديك اسهال؟", "ans": 2 } ]""";
    var map = json.decode(questionsJson) as List;
    return map;
  }

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