import 'package:auto_size_text/auto_size_text.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/models/gradient_color.dart';
import 'package:diplomaticquarterapp/models/hmg_services.dart';
import 'package:diplomaticquarterapp/models/slider_data.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/all_habib_medical_service_page.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/MyAppointments.dart';
import 'package:diplomaticquarterapp/pages/landing/widgets/logged_slider_view.dart';
import 'package:diplomaticquarterapp/pages/landing/widgets/pharmacy_view.dart';
import 'package:diplomaticquarterapp/pages/landing/widgets/services_view.dart';
import 'package:diplomaticquarterapp/pages/landing/widgets/slider_view.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page_new.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.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/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart' as s;
import 'package:provider/provider.dart';

class LoggedHomePageFragment extends StatefulWidget {
  ProjectViewModel projectViewModel;
  Function onPharmacyClick;

  LoggedHomePageFragment(this.projectViewModel, {this.onPharmacyClick});

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

class _HomePageFragmentState extends State<LoggedHomePageFragment> {
  List<HmgServices> hmgServices = [];
  var familyFileProvider = FamilyFilesProvider();
  List<AppoitmentAllHistoryResultList> appoList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getPatientAppointmentHistory1();
    // getPatientAppointmentHistory1();
    //  getFamilyFiles();
  }

  initialiseHmgServices(bool isLogin) {
    hmgServices.clear();
    hmgServices.add(new HmgServices(0, TranslationBase.of(context).liveCare, TranslationBase.of(context).onlineConsulting, "assets/images/new/Live_Care.svg", isLogin));
    hmgServices.add(new HmgServices(1, TranslationBase.of(context).covidTest, TranslationBase.of(context).driveThru, "assets/images/new/covid_test_drive_thru.svg", isLogin));
    hmgServices.add(new HmgServices(2, TranslationBase.of(context).checkup, TranslationBase.of(context).comprehensive, "assets/images/new/comprehensive_checkup.svg", isLogin));
    hmgServices.add(new HmgServices(3, TranslationBase.of(context).hhcHome, TranslationBase.of(context).healthCare, "assets/images/new/HHC.svg", isLogin));
    hmgServices.add(new HmgServices(4, TranslationBase.of(context).refferal, TranslationBase.of(context).services2, "assets/images/new/E_Refferal.svg", isLogin));
    hmgServices.add(new HmgServices(5, "RRT", TranslationBase.of(context).emergency, "assets/images/new/RRT.svg", isLogin));
  }

  Future<GetAllSharedRecordsByStatusResponse> getFamilyFiles() async {
    if (widget.projectViewModel.user != null) {
      print("calling_family");

      if (await s.sharedPref.getObject(FAMILY_FILE) != null) {
        // print(await sharedPref.getObject(FAMILY_FILE));
        return Future.value(GetAllSharedRecordsByStatusResponse.fromJson(await s.sharedPref.getObject(FAMILY_FILE)));
      } else {
        return familyFileProvider.getSharedRecordByStatus();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    initialiseHmgServices(false);
    var appoCountProvider = Provider.of<ToDoCountProviderModel>(context);
    List<Widget> myMedicalList = Utils.myMedicalListHomePage(projectViewModel: widget.projectViewModel, context: context, count: appoCountProvider.count, isLogin: widget.projectViewModel.isLogin);
    return Container(
      width: double.infinity,
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 2.3,
            child: Padding(
              padding: const EdgeInsets.only(left: 20, right: 20, top: 16, bottom: 16),
              child: LoggedSliderView(
                  widget.projectViewModel,
                  new SliderData(TranslationBase.of(context).fileno + ": " + widget.projectViewModel.user.patientID.toString(),
                      widget.projectViewModel.user.firstName + ' ' + widget.projectViewModel.user.lastName, "", bannerColor[0].darkColor, bannerColor[0].lightColor),null),
            ),
          ),
          appoCountProvider.count == 0
              ? Padding(
                  padding: const EdgeInsets.only(left: 20, right: 20),
                  child: Image.asset("assets/images/bn_offer.png"),
                )
              : offersView(appoCountProvider.count),
          mHeight(16),
          Container(
            width: double.infinity,
            height: MediaQuery.of(context).size.width * 0.26,
            child: ListView.separated(
              itemCount: 4,
              padding: EdgeInsets.zero,
              scrollDirection: Axis.horizontal,
              physics: BouncingScrollPhysics(),
              itemBuilder: (context, index) {
                return widget.projectViewModel.isArabic
                    ? Container(
                        child: myMedicalList[index],
                        width: MediaQuery.of(context).size.width * 0.26,
                        margin: EdgeInsets.only(left: index == 3 ? 20 : 0, right: index == 0 ? 20 : 0),
                      )
                    : Container(
                        child: myMedicalList[index],
                        width: MediaQuery.of(context).size.width * 0.26,
                        margin: EdgeInsets.only(left: index == 0 ? 20 : 0, right: index == 3 ? 20 : 0),
                      );
              },
              separatorBuilder: (BuildContext context, int index) {
                return mWidth(12);
              },
            ),
          ),
          Padding(
            padding: widget.projectViewModel.isArabic
                ? EdgeInsets.only(
                    right: 20,
                    left: 8,
                    top: 0,
                  )
                : EdgeInsets.only(
                    left: 20,
                    right: 8,
                    top: 0,
                  ),
            child: Row(
              children: [
                mFlex(1),
                FlatButton(
                  onPressed: () {
                    navigateTo(context, MedicalProfilePageNew());
                  },
                  child: Text(
                    TranslationBase.of(context).viewMedicalFile,
                    style: TextStyle(
                      color: CustomColors.accentColor,
                      fontSize: 14,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
              top: 4,
            ),
            child: PharmacyView(
              onPharmacyClick: () {
                widget.onPharmacyClick();
              },
            ),
          ),
          Column(
            children: [
              Padding(
                padding: widget.projectViewModel.isArabic
                    ? EdgeInsets.only(
                        right: 20,
                        left: 8,
                        top: 4,
                      )
                    : EdgeInsets.only(
                        left: 20,
                        right: 8,
                        top: 4,
                      ),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        TranslationBase.of(context).hMGService,
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    FlatButton(
                      onPressed: () {
                        Navigator.push(context, FadePage(page: AllHabibMedicalService()));
                      },
                      child: Text(
                        TranslationBase.of(context).viewAllServices,
                        style: TextStyle(
                          color: CustomColors.accentColor,
                          fontSize: 14,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              mHeight(4),
              Container(
                width: double.infinity,
                height: MediaQuery.of(context).size.width * 0.26,
                child: ListView.separated(
                  itemCount: hmgServices.length,
                  padding: EdgeInsets.zero,
                  scrollDirection: Axis.horizontal,
                  physics: BouncingScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      width: MediaQuery.of(context).size.width * 0.26,
                      margin: widget.projectViewModel.isArabic
                          ? EdgeInsets.only(left: index == hmgServices.length - 1 ? 20 : 0, right: index == 0 ? 20 : 0)
                          : EdgeInsets.only(left: index == 0 ? 20 : 0, right: index == hmgServices.length - 1 ? 20 : 0),
                      child: ServicesView(hmgServices[index], index),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return mWidth(12);
                  },
                ),
              ),
            ],
          ),
          mHeight(140),
        ],
      ),
    );
  }

  Widget offersView(int counts) {
    if (appoList.length > 0) {
      return Container(
        height: MediaQuery.of(context).size.width / 4.35,
        child: ListView.separated(
          itemCount: 2,
          padding: EdgeInsets.zero,
          scrollDirection: Axis.horizontal,
          physics: BouncingScrollPhysics(),
          itemBuilder: (context, index) {
            return index == 0
                ? Container(
                    width: MediaQuery.of(context).size.width / 1.123,
                    height: MediaQuery.of(context).size.width / 4.35,
                    margin: widget.projectViewModel.isArabic ? EdgeInsets.only(right: index == 0 ? 20 : 0) : EdgeInsets.only(left: index == 0 ? 20 : 0),
                    padding: EdgeInsets.all(8),
                    decoration: containerColorRadiusBorderWidth(Colors.white, 16, Colors.black, 2),
                    child: InkWell(
                      onTap: () {},
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          circularAviator(MediaQuery.of(context).size.width / 10, brColor: Colors.white, elevation: 1),
                          mWidth(8),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            appoList[index].doctorTitle + " " + appoList[index].doctorNameObj,
                                            style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 16,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            children: [
                                              Icon(
                                                Icons.watch_later_rounded,
                                                size: 16,
                                              ),
                                              mWidth(4),
                                              Expanded(
                                                child: AutoSizeText(
                                                  DateUtil.getWeekDayMonthDayYearDateFormatted(
                                                          DateUtil.convertStringToDate(appoList[index].appointmentDate), widget.projectViewModel.isArabic ? "ar" : "en") +
                                                      " " +
                                                      appoList[index].startTime.substring(0, 5),
                                                  maxLines: 1,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      children: [
                                        Icon(
                                          Icons.notifications_active_sharp,
                                          color: Color(0xFF9D9D9D),
                                          size: 16,
                                        ),
                                        mWidth(4),
                                        Text(
                                          "Remind me",
                                          style: TextStyle(
                                            color: Color(0xFF9D9D9D),
                                            fontSize: 12,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                mFlex(1),
                                Flexible(
                                  child: Container(
                                    width: double.infinity,
                                    child: Row(
                                      children: [
                                        // Text(
                                        //   "Appointment Details",
                                        //   style: TextStyle(
                                        //     color: CustomColors.accentColor,
                                        //     decoration: TextDecoration.underline,
                                        //   ),
                                        // ),
                                        FlatButton(
                                          onPressed: () {
                                            Navigator.push(context, FadePage(page: MyAppointments()));
                                          },
                                          child: Text(
                                            "Appointment Details",
                                            style: TextStyle(
                                              color: CustomColors.accentColor,
                                              fontSize: 14,
                                              decoration: TextDecoration.underline,
                                            ),
                                          ),
                                        ),
                                        mFlex(1),
                                        Icon(Icons.arrow_forward),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                : Padding(
                    padding: widget.projectViewModel.isArabic ? EdgeInsets.only(left: index == 1 ? 20 : 0) : EdgeInsets.only(right: index == 1 ? 20 : 0),
                    child: Container(
                      child: showOfferImage(),
                      width: MediaQuery.of(context).size.width / 1.123,
                    ),
                  );
          },
          separatorBuilder: (BuildContext context, int index) {
            return mWidth(12);
          },
        ),
      );
    } else {
      return Padding(
        padding: const EdgeInsets.only(left: 20, right: 20),
        child: Image.asset("assets/images/bn_offer.png"),
      );
    }
  }

  Widget showOfferImage() {
    return Image.asset(
      "assets/images/bn_offer.png",
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.fill,
    );
  }

  getPatientAppointmentHistory1() async {
    DoctorsListService service = new DoctorsListService();

    Map res = await service.getPatientAppointmentHistory(true, context);
    // appoList.clear();
    if (res['MessageStatus'] == 1) {
      if (res['AppoimentAllHistoryResultList'].length != 0) {
        appoList.clear();
        res['AppoimentAllHistoryResultList'].forEach((v) {
          appoList.add(new AppoitmentAllHistoryResultList.fromJson(v));
        });
      }
    }
    setState(() {});
  }
}
