import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/medical_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/DoctorScheduleResponse.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/indicator.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SchedulePage extends StatefulWidget {
  DoctorList doctorList;
  AppoitmentAllHistoryResultList appo;

  SchedulePage({
    this.appo,
    this.doctorList,
  });

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

class _SchedulePageState extends State<SchedulePage> {
  DoctorsListService service;
  PageController _pageController = PageController();
  double currentPage = 0;
  int selectedindex = 0;
  List weeks = [];
  List<DoctorScheduleResponse> doctorScheduleResponse = [];
  int weekMS = 604800 * 1000;
  DoctorList doctorList;
  List<String> freeSlots = [];
  bool isPageChange = false;

  AppSharedPreferences sharedPref = AppSharedPreferences();

  @override
  void initState() {
    this.doctorList = widget.doctorList;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<MedicalViewModel>(
        onModelReady: (model) => model.getDoctorSchedule(doctorList),
        allowAny: true,
        builder: (_, model, widget) => BaseView<MedicalViewModel>(
            onModelReady: (model2) => model2.getFreeSlots(doctorList),
            allowAny: true,
            builder: (_, model2, widget2) {
              if (model2.freeSlots.length > 0 && isPageChange == false && model2.state == ViewState.Idle) {
                this.freeSlots = model2.freeSlots;
                this.doctorScheduleResponse = model.getDoctorScheduleList;

                this.generateWeeksSchedules();
              } else if (model2.freeSlots.length == 0 && model2.state == ViewState.Idle) {
                AppToast.showErrorToast(message: TranslationBase.of(context).emptySchedule);
                Navigator.pop(context);
              }
              return AppScaffold(
                  appBarTitle: TranslationBase.of(context).schedule,
                  showNewAppBar: true,
                  showNewAppBarTitle: true,
                  isShowAppBar: true,
                  baseViewModel: model2,
                  isShowDecPage: false,
                  body: SizedBox(
                      height: MediaQuery.of(context).size.height,
                      child: Stack(
                        children: [
                          Container(
                              margin: EdgeInsets.only(top: 40),
                              child: PageView.builder(
                                controller: _pageController,
                                itemCount: weeks.length,
                                onPageChanged: (index) {
                                  setState(() {
                                    isPageChange = true;
                                    this.currentPage = index.toDouble();
                                  });
                                },
                                itemBuilder: (context, index) {
                                  return Container(
                                      child: ListView.builder(
                                          itemCount: weeks[index].length,
                                          itemBuilder: (context, index2) => InkWell(
                                              onTap: () {
                                                final weekDay = weeks[index][index2]['DayName'];
                                                openBookAppointment(weeks[index][index2]);
                                                projectViewModel.analytics.appointment.book_appointment_date_selection(appointment_type: 'regular', day: weekDay, doctor: doctorList);
                                              },
                                              child: Row(
                                                children: [
                                                  Expanded(
                                                    flex: 1,
                                                    child: Padding(
                                                        padding: projectViewModel.isArabic ? EdgeInsets.only(right: 20) : EdgeInsets.only(left: 20),
                                                        child: Row(children: [
                                                          Column(
                                                            children: [
                                                              Texts(
                                                                weeks[index][index2]['DayName'],
                                                                fontSize: 13,
                                                                fontWeight: projectViewModel.isArabic ? FontWeight.w600 : FontWeight.w500,
                                                              ),
                                                              Texts(
                                                                getDayMonths(
                                                                  DateUtil.convertStringToDate(
                                                                    weeks[index][index2]['Date'],
                                                                  ),
                                                                ),
                                                                fontWeight: FontWeight.bold,
                                                                fontSize: 18,
                                                              )
                                                            ],
                                                          )
                                                        ])),
                                                  ),
                                                  Expanded(
                                                    flex: 3,
                                                    child: ClipRRect(
                                                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                                                        child: Container(
                                                            padding: EdgeInsets.only(left: 10, right: 10, top: 15, bottom: 20),
                                                            margin: EdgeInsets.only(left: 20, right: 20, top: 7, bottom: 7),
                                                            decoration: BoxDecoration(boxShadow: [
                                                              DateUtil.convertStringToDate(weeks[index][index2]['Date']).toString().substring(0, 10) == DateTime.now().toString().substring(0, 10)
                                                                  ? BoxShadow(color: Colors.green, offset: Offset(projectViewModel.isArabic ? 5 : -5, 0))
                                                                  : BoxShadow(
                                                                      color: Colors.grey[100],
                                                                      blurRadius: 5,
                                                                      spreadRadius: 4,
                                                                      offset: Offset(0, 10),
                                                                    ),
                                                            ], borderRadius: const BorderRadius.all(Radius.circular(10.0)), color: Colors.white),
                                                            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                                              DateUtil.convertStringToDate(weeks[index][index2]['Date']).toString().substring(0, 10) == DateTime.now().toString().substring(0, 10)
                                                                  ? Texts(
                                                                      TranslationBase.of(context).today,
                                                                      color: Colors.green,
                                                                      fontWeight: FontWeight.w600,
                                                                      fontSize: 12,
                                                                      marginTop: 0,
                                                                    )
                                                                  : SizedBox(),
                                                              Row(
                                                                children: [
                                                                  Expanded(
                                                                    child: Text(
                                                                      weeks[index][index2]['WorkingHours'],
                                                                      style: TextStyle(
                                                                        fontWeight: FontWeight.w600,
                                                                      ),
                                                                    ),
                                                                  ),
                                                                  Icon(Icons.arrow_forward, size: 16.0),
                                                                ],
                                                              )
                                                            ]))),
                                                  ),
                                                ],
                                              ))));
                                },
                              )),
                          PageViewIndicator(
                            isActive: true,
                            currentPage: this.currentPage,
                            length: weeks.length,
                          )
                        ],
                      )));
            }));
  }

  generateWeeksSchedules() {
    this.weeks.clear();
    for (var i = 0; i < 8; i++) {
      var weekSchedule = generateNewWeekSchedule(i);
      this.markWeekFreeDays(weekSchedule);
      this.weeks.add(weekSchedule);
    }
    //print(this.weeks);
  }

  markWeekFreeDays(schedule) {
    for (var workDay in schedule) {
      workDay['fullDay'] = !this.hasFreeSlot(workDay['Date']);
    }
  }

  generateNewWeekSchedule(weekIndex) {
    var weekMSOffset = weekIndex * weekMS;

    var newWeekSchedule = [];
    for (var workDay in this.doctorScheduleResponse) {
      Map<String, dynamic> newWorkDay = Map();
      newWorkDay['Date'] = DateUtil.convertDateMSToJsonDate(DateUtil.convertStringToDate(workDay.date).millisecondsSinceEpoch + weekMSOffset);
      newWorkDay['DayName'] = workDay.dayName;
      newWorkDay['WorkingHours'] = workDay.workingHours;
      newWeekSchedule.add(newWorkDay);
    }
    return newWeekSchedule;
  }

  hasFreeSlot(String jsonDate) {
    var date = DateUtil.convertStringToDate(jsonDate);
    var scheduleDay = date;
    for (var event in this.freeSlots) {
      var date = DateUtil.convertStringToDate(event);
      var nDate = DateTime(date.year, date.month, date.day);

      if (nDate.millisecondsSinceEpoch == scheduleDay.millisecondsSinceEpoch) {
        return true;
      }
    }
    return false;
  }

  String getDayMonths(DateTime dateTime) {
    String dateFormat = '${dateTime.day} ${DateUtil.getMonth(dateTime.month).toString().substring(0, 3)}';
    return dateFormat;
  }

  openBookAppointment(selectedDate) {
    //sharedPref.setObject(DOCTOR_SCHEDULE_DATE_SEL, selectedDate);
    Navigator.of(context).pop(selectedDate);
    // Navigator.push(
    //   context,
    //   FadePage(
    //     page: AppointmentDetails(
    //       appo: widget.appo,
    //       doctorSchedule: selectedDate,
    //     ),
    //   ),
    // );
  }
}

// import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
// import 'package:diplomaticquarterapp/pages/MyAppointments/AppointmentDetails.dart';
//
// import 'package:diplomaticquarterapp/pages/MyAppointments/models/DoctorScheduleResponse.dart';
// import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/indicator.dart';
// import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
// import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
// import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
// import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
// import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
// import 'package:flutter/material.dart';
// import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
// import 'package:diplomaticquarterapp/core/viewModels/medical/medical_view_model.dart';
// import 'package:diplomaticquarterapp/pages/base/base_view.dart';
// import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
// import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
// import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
// import 'package:diplomaticquarterapp/uitl/app_toast.dart';
// import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
// import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
// import 'package:provider/provider.dart';
// import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
//
// class SchedulePage extends StatefulWidget {
//   DoctorList doctorList;
//   AppoitmentAllHistoryResultList appo;
//   SchedulePage({
//     this.appo,
//     this.doctorList,
//   });
//   @override
//   _SchedulePageState createState() => _SchedulePageState();
// }
//
// class _SchedulePageState extends State<SchedulePage> {
//   DoctorsListService service;
//   PageController _pageController = PageController();
//   double currentPage = 0;
//   int selectedindex = 0;
//   List weeks = [];
//   List<DoctorScheduleResponse> doctorScheduleResponse = [];
//   int weekMS = 604800 * 1000;
//   DoctorList doctorList;
//   List<String> freeSlots = [];
//   bool isPageChange = false;
//
//   AppSharedPreferences sharedPref = AppSharedPreferences();
//   @override
//   void initState() {
//     this.doctorList = widget.doctorList;
//
//     super.initState();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     ProjectViewModel projectViewModel = Provider.of(context);
//     return BaseView<MedicalViewModel>(
//       onModelReady: (model) => model.getDoctorSchedule(doctorList),
//       allowAny: true,
//       builder: (_, model, widget) => BaseView<MedicalViewModel>(
//           onModelReady: (model2) => model2.getFreeSlots(doctorList),
//           allowAny: true,
//           builder: (_, model2, widget2) {
//             if (model2.freeSlots.length > 0 && isPageChange == false && model2.state == ViewState.Idle) {
//               this.freeSlots = model2.freeSlots;
//               this.doctorScheduleResponse = model.getDoctorScheduleList;
//
//               this.generateWeeksSchedules();
//             } else if (model2.freeSlots.length == 0 && model2.state == ViewState.Idle) {
//               AppToast.showErrorToast(message: TranslationBase.of(context).emptySchedule);
//               Navigator.pop(context);
//             }
//             return AppScaffold(
//               appBarTitle: TranslationBase.of(context).schedule,
//               showNewAppBar: true,
//               showNewAppBarTitle: true,
//               isShowAppBar: true,
//               backgroundColor: Color(0xffF7F7F7),
//               baseViewModel: model2,
//               isShowDecPage: false,
//               body: Column(
//                 children: [
//                   SizedBox(height: 21),
//                   PageViewIndicator(
//                     isActive: true,
//                     currentPage: this.currentPage,
//                     length: weeks.length,
//                   ),
//                   Expanded(
//                     child: PageView.builder(
//                       controller: _pageController,
//                       itemCount: weeks.length,
//                       onPageChanged: (index) {
//                         setState(() {
//                           isPageChange = true;
//                           this.currentPage = index.toDouble();
//                         });
//                       },
//                       itemBuilder: (context, index) {
//                         return ListView.separated(
//                             itemCount: weeks[index].length,
//                             padding: EdgeInsets.all(21),
//                             separatorBuilder: (context, index) => SizedBox(height: 12),
//                             itemBuilder: (context, index2) {
//                               bool isToday = DateUtil.convertStringToDate(weeks[index][index2]['Date']).toString().substring(0, 10) == DateTime.now().toString().substring(0, 10);
//                               Color toDayColor = isToday ? Color(0xff359846) : Colors.white;
//                               return InkWell(
//                                 onTap: () {
//                                   openBookAppointment(weeks[index][index2]);
//                                 },
//                                 child: Row(
//                                   crossAxisAlignment: CrossAxisAlignment.start,
//                                   children: [
//                                     Expanded(
//                                       flex: 1,
//                                       child: Column(
//                                         mainAxisSize: MainAxisSize.min,
//                                         crossAxisAlignment: CrossAxisAlignment.start,
//                                         children: [
//                                           Text(
//                                             weeks[index][index2]['DayName'],
//                                             style: TextStyle(
//                                               fontSize: 13,
//                                               fontWeight: FontWeight.w600,
//                                               color: Color(0xff2E303A),
//                                               letterSpacing: -0.52,
//                                             ),
//                                           ),
//                                           Text(
//                                             getDayMonths(DateUtil.convertStringToDate(weeks[index][index2]['Date'])),
//                                             style: TextStyle(
//                                               fontSize: 18,
//                                               fontWeight: FontWeight.w700,
//                                               color: Color(0xff2E303A),
//                                               letterSpacing: -0.72,
//                                             ),
//                                           ),
//                                         ],
//                                       ),
//                                     ),
//                                     Expanded(
//                                       flex: 3,
//                                       child: Container(
//                                         decoration: BoxDecoration(
//                                           color: toDayColor,
//                                           borderRadius: BorderRadius.all(
//                                             Radius.circular(10.0),
//                                           ),
//                                           boxShadow: [
//                                             BoxShadow(
//                                               color: Color(0xff000000).withOpacity(.05),
//                                               blurRadius: 27,
//                                               offset: Offset(0, -3),
//                                             ),
//                                           ],
//                                         ),
//                                         child: Container(
//                                           margin: EdgeInsets.only(left: projectViewModel.isArabic ? 0 : 6, right: projectViewModel.isArabic ? 6 : 0),
//                                           padding: EdgeInsets.symmetric(vertical: 14, horizontal: 12),
//                                           decoration: BoxDecoration(
//                                             color: Colors.white,
//                                             border: Border.all(color: Colors.white, width: 1),
//                                             borderRadius: BorderRadius.only(
//                                               bottomRight: projectViewModel.isArabic ? Radius.circular(0) : Radius.circular(10.0),
//                                               topRight: projectViewModel.isArabic ? Radius.circular(0) : Radius.circular(10.0),
//                                               bottomLeft: projectViewModel.isArabic ? Radius.circular(10.0) : Radius.circular(0),
//                                               topLeft: projectViewModel.isArabic ? Radius.circular(10.0) : Radius.circular(0),
//                                             ),
//                                           ),
//                                           child: Row(
//                                             crossAxisAlignment: CrossAxisAlignment.center,
//                                             children: [
//                                               Expanded(
//                                                 child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
//                                                   if (isToday)
//                                                     Text(
//                                                       TranslationBase.of(context).today,
//                                                       style: TextStyle(
//                                                         fontSize: 12,
//                                                         fontWeight: FontWeight.w600,
//                                                         color: toDayColor,
//                                                         letterSpacing: -0.48,
//                                                       ),
//                                                     ),
//                                                   Row(
//                                                     children: [
//                                                       Expanded(
//                                                         child: Text(
//                                                           weeks[index][index2]['WorkingHours'],
//                                                           style: TextStyle(
//                                                             fontSize: 13,
//                                                             fontWeight: FontWeight.w600,
//                                                             color: Color(0xff2E303A),
//                                                             letterSpacing: -0.56,
//                                                           ),
//                                                         ),
//                                                       ),
//                                                     ],
//                                                   )
//                                                 ]),
//                                               ),
//                                               Icon(Icons.arrow_forward, color: Color(0xff2B353E)),
//                                             ],
//                                           ),
//                                         ),
//                                       ),
//                                     ),
//                                   ],
//                                 ),
//                               );
//                             });
//                       },
//                     ),
//                   ),
//                 ],
//               ),
//             );
//           }),
//     );
//   }
//
//   generateWeeksSchedules() {
//     this.weeks.clear();
//     for (var i = 0; i < 8; i++) {
//       var weekSchedule = generateNewWeekSchedule(i);
//       this.markWeekFreeDays(weekSchedule);
//       this.weeks.add(weekSchedule);
//     }
//     //print(this.weeks);
//   }
//
//   markWeekFreeDays(schedule) {
//     for (var workDay in schedule) {
//       workDay['fullDay'] = !this.hasFreeSlot(workDay['Date']);
//     }
//   }
//
//   generateNewWeekSchedule(weekIndex) {
//     var weekMSOffset = weekIndex * weekMS;
//
//     var newWeekSchedule = [];
//     for (var workDay in this.doctorScheduleResponse) {
//       Map<String, dynamic> newWorkDay = Map();
//       newWorkDay['Date'] = DateUtil.convertDateMSToJsonDate(DateUtil.convertStringToDate(workDay.date).millisecondsSinceEpoch + weekMSOffset);
//       newWorkDay['DayName'] = workDay.dayName;
//       newWorkDay['WorkingHours'] = workDay.workingHours;
//       newWeekSchedule.add(newWorkDay);
//     }
//     return newWeekSchedule;
//   }
//
//   hasFreeSlot(String jsonDate) {
//     var date = DateUtil.convertStringToDate(jsonDate);
//     var scheduleDay = date;
//     for (var event in this.freeSlots) {
//       var date = DateUtil.convertStringToDate(event);
//       var nDate = DateTime(date.year, date.month, date.day);
//
//       if (nDate.millisecondsSinceEpoch == scheduleDay.millisecondsSinceEpoch) {
//         return true;
//       }
//     }
//     return false;
//   }
//
//   String getDayMonths(DateTime dateTime) {
//     String dateFormat = '${dateTime.day} ${DateUtil.getMonth(dateTime.month).toString().substring(0, 3)}';
//     return dateFormat;
//   }
//
//   openBookAppointment(selectedDate) {
//     //sharedPref.setObject(DOCTOR_SCHEDULE_DATE_SEL, selectedDate);
//     Navigator.of(context).pop(selectedDate);
//     // Navigator.push(
//     //   context,
//     //   FadePage(
//     //     page: AppointmentDetails(
//     //       appo: widget.appo,
//     //       doctorSchedule: selectedDate,
//     //     ),
//     //   ),
//     // );
//   }
// }
