import 'package:hmg_patient_app/config/size_config.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/medical/medical_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/services/authentication/auth_provider.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/widgets/data_display/medical/time_line_new_widget.dart';
import 'package:hmg_patient_app/widgets/dialogs/radio_selection_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class MedicalProfilePageNew extends StatefulWidget {
  Function()? onTap;
  String? a;

  MedicalProfilePageNew({this.onTap});

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

class _MedicalProfilePageState extends State<MedicalProfilePageNew> {
  var authProvider = new AuthProvider();
  List<Medical> medical = [];
  ProjectViewModel? projectViewModel;

  List<HospitalsModel> projectsList = [];
  HospitalsModel? _selectedHospital;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    var appoCountProvider = Provider.of<ToDoCountProviderModel>(context);
    List<Widget> myMedicalList =
        Utils.myMedicalList(projectViewModel: projectViewModel!, context: context, count: appoCountProvider.count, isLogin: projectViewModel!.isLogin, onWeCareClick: openWeCareProjectSelection);
    return BaseView<MedicalViewModel>(
      onModelReady: (model) => model.getAppointmentHistory(isForTimeLine: true),
      builder: (_, model, widget1) => AppScaffold(
        isShowDecPage: false,
        isShowAppBar: false,
        baseViewModel: model,
        showNewAppBar: true,
        isHelp: true,
        showNewAppBarTitle: true,
        appBarTitle: TranslationBase.of(context).medicalFileTitle,
        onTap: widget.onTap,
        body: Container(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                TimeLineView(model.isLogin, projectViewModel!.isArabic, model.appoitmentAllHistoryResultList, model),
                SizedBox(
                  height: 20,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 12, right: 12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      projectViewModel!.isLogin
                          ? Text(
                              projectViewModel?.user.firstName ?? "",
                              style: TextStyle(color: Colors.black, fontSize: SizeConfig.textMultiplier! * 1.8),
                            )
                          : Container(),
                      Text(
                        TranslationBase.of(context).medicalFileTitle,
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: SizeConfig.textMultiplier! * 3,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 12, right: 12),
                  child: GridView.builder(
                    shrinkWrap: true,
                    primary: false,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 2 / 2, crossAxisSpacing: 12, mainAxisSpacing: 12),
                    padding: EdgeInsets.zero,
                    itemCount: myMedicalList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return myMedicalList[index];
                    },
                  ),
                ),
                SizedBox(
                  height: 12,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  openWeCareProjectSelection() {
    int _selectedHospitalIndex = -1;
    int languageID = projectViewModel!.isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    service.getProjectsList(languageID, context).then((res) {
      if (res['MessageStatus'] == 1) {
        setState(() {
          res['ListProject'].forEach((v) {
            projectsListLocal.add(new HospitalsModel.fromJson(v));
          });
          projectsList = projectsListLocal;
        });
        GifLoaderDialogUtils.hideDialog(context);
        List<RadioSelectionDialogModel> list = [
          for (int i = 0; i < projectsList.length; i++) RadioSelectionDialogModel(projectsList[i].name! + ' ${projectsList[i].distanceInKilometers} ' + TranslationBase.of(context).km, i),
        ];
        showDialog(
          context: context,
          builder: (cxt) => RadioSelectionDialog(
            buttonText: TranslationBase.of(context).confirm,
            listData: list,
            selectedIndex: _selectedHospitalIndex,
            isScrollable: true,
            onValueSelected: (index) {
              _selectedHospitalIndex = index;
              _selectedHospital = projectsList[index];
              openWeCareURL(_selectedHospital!.iD);
              // setState(() {});
            },
          ),
        );
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      print(err);
    });
  }

  openWeCareURL(int projectID) {
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    service.getWeCareURL(projectID).then((res) {
      print(res["Consent_VirtualJurny_Url_GetByProjectIDList"][0]["Url"]);
      Uri uri = Uri.parse(res["Consent_VirtualJurny_Url_GetByProjectIDList"][0]["Url"]);
      GifLoaderDialogUtils.hideDialog(context);
      launchUrl(uri, mode: LaunchMode.inAppWebView);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err.toString());
    });
  }
}

class Medical {
  final String? title;
  final String? imagePath;
  final String? subTitle;
  final Widget? page;

  Medical({this.title, this.imagePath, this.subTitle, this.page});
}
