import 'package:doctor_app_flutter/core/service/home/dasboard_service.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../../core/viewModel/project_view_model.dart';
import '../../core/viewModel/schedule_view_model.dart';
import '../../icons_app/doctor_app_icons.dart';
import '../../utils/date-utils.dart';
import '../../utils/translations_delegate_base_utils.dart';
import '../../widgets/shared/app_scaffold_widget.dart';
import '../../widgets/shared/errors/error_message.dart';
import '../base/base_view.dart';


class DoctorSchedulePage extends StatefulWidget {
  @override
  _DoctorSchedulePageState createState() => _DoctorSchedulePageState();
}

class _DoctorSchedulePageState extends State<DoctorSchedulePage> {
  late DashboardService service;
  PageController _pageController = PageController();
  double currentPage = 0;
  int selectedindex = 0;
  List weeks = [];
  int weekMS = 604800 * 1000;

  List<String> freeSlots = [];
  bool isPageChange = false;
  String fromDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
  String toDate =
      DateFormat('yyyy-MM-dd').format(DateTime.now().add(Duration(days: 30)));
  int pageNo=1;
  @override
  void initState() {

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<ScheduleViewModel>(
        onModelReady: (model) => model.getDoctorRota(fromDate, toDate),
        builder: (_, model, widget2) {
          return AppScaffold(
            appBarTitle: TranslationBase.of(context).doctorSchedule,
            isShowAppBar: true,
            baseViewModel: model,
            isHomeIcon: false,
            isLoading: true,
            actionButton: IconButton(
              icon: Icon(DoctorApp.search_1),
              color: Colors.black, //Colors.black,
              onPressed: () => searchSchedule(model),
            ),
            body: SizedBox(
                height: MediaQuery.of(context).size.height,
                child: Stack(
                  children: [
                    Column(
                      children: [
                        Padding(
                            padding: EdgeInsets.only(left: 20),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  TranslationBase.of(context).dateFrom +
                                      " " +
                                      DateFormat("dd-MMM").format(DateFormat('yyyy-MM-dd').parse(fromDate)) +
                                      " " +
                                      TranslationBase.of(context).to +
                                      " " +
                                      DateFormat("dd-MMM").format(DateFormat('yyyy-MM-dd').parse(toDate)),
                                  style: TextStyle(fontWeight: FontWeight.w600),
                                ),
                                Row(
                                  children: [
                                    IconButton(
                                        onPressed: () {

                                         if(pageNo >1) {
                                           pageNo--;
                                           model.getDoctorRota(fromDate, toDate,
                                               pageNo: pageNo);
                                         }
                                        },
                                        icon: SvgPicture.asset(
                                            'assets/images/svgs/prev.svg',
                                            height: 25,
                                            width: 10)),
                                    IconButton(
                                        onPressed: () {
                                          pageNo++;
                                          model.getDoctorRota(fromDate, toDate, pageNo: pageNo);
                                        },
                                        icon: SvgPicture.asset(
                                            'assets/images/svgs/next.svg',
                                            height: 25,
                                            width: 10))
                                  ],
                                ),
                              ],
                            )),
                      ],
                    ),
           model.getDoctorRotation.length ==0 ? Center(
           child: ErrorMessage(
           error: TranslationBase.of(context).noDataAvailable,
           )) :
                    Container(
                        margin: EdgeInsets.only(top: 45),
                        child: PageView.builder(
                          controller: _pageController,
                          itemCount: model.getDoctorRotation.length,
                          onPageChanged: (index) {
                            setState(() {
                              isPageChange = true;
                              this.currentPage = index.toDouble();
                            });
                          },
                          itemBuilder: (context, index) {
                            return model.getDoctorRotation[index]
                                .scheduleforuser!.length ==0  ?  Center(
                                child: ErrorMessage(
                                  error: TranslationBase.of(context).noDataAvailable,
                                )) :    Container(
                                child: ListView.builder(
                                    itemCount: model.getDoctorRotation[index]
                                        .scheduleforuser!.length,
                                    itemBuilder: (context, index2) => InkWell(
                                        onTap: () {
                                          // final weekDay = weeks[index][index2]['DayName'];
                                        },
                                        child: Row(
                                          children: [
                                            Expanded(
                                              flex: 1,
                                              child: Padding(
                                                  padding:
                                                      projectViewModel.isArabic
                                                          ? EdgeInsets.only(
                                                              right: 17)
                                                          : EdgeInsets.only(
                                                              left: 17),
                                                  child: Row(children: [
                                                    Column(
                                                      children: [
                                                        Text(DateFormat('EEEE')
                                                                .format(model
                                                                    .getDoctorRotation[
                                                                        index]
                                                                    .scheduleforuser![
                                                                        index2]
                                                                    .days!)

                                                                // fontSize: 13,
                                                                // fontWeight: projectViewModel.isArabic ? FontWeight.w600 : FontWeight.w500,
                                                                ),
                                                            Text(getDayMonths(model.getDoctorRotation[index].scheduleforuser![index2].days))

                                                            // 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: [
                                                            model.getDoctorRotation[index].scheduleforuser![index2].days.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: [
                                                            model.getDoctorRotation[index].scheduleforuser![index2].days.toString().substring(0, 10) == DateTime.now().toString().substring(0, 10)
                                                                ? Text(TranslationBase.of(context).today,
                                                                    style: TextStyle(
                                                                      color: Colors.green,
                                                                      fontWeight: FontWeight.w600,
                                                                      fontSize: 12,
                                                                    ))
                                                                : SizedBox(),
                                                            //     : SizedBox(),
                                                            Row(
                                                              children: [
                                                                Expanded(
                                                                  child: Text(
                                                                    model.getDoctorRotation[index].clinicname!,
                                                                    style: TextStyle(
                                                                      fontWeight: FontWeight.w600,
                                                                    ),
                                                                  ),
                                                                ),
                                                                // Icon(Icons.arrow_forward, size: 16.0),
                                                              ],
                                                            ),
                                                            Container(
                                                                height: 45,
                                                                child: ListView
                                                                    .builder(
                                                                        itemCount: model
                                                                            .getDoctorRotation[
                                                                                index]
                                                                            .scheduleforuser![
                                                                                index2]
                                                                            .shiftforuser
                                                                            !.length,
                                                                        itemBuilder: (context,
                                                                                index3) =>
                                                                            Row(children: [
                                                                              Text(model.getDoctorRotation[index].scheduleforuser![index2].shiftforuser![index3].fromtimetext.toString()),
                                                                              Text(" "+TranslationBase.of(context).to +" "),
                                                                              Text(model.getDoctorRotation[index].scheduleforuser![index2].shiftforuser![index3].totimetext.toString())
                                                                            ])))

                                                            //  ],)
                                                          ]))),
                                                ),
                                              ],
                                            ))));
                              },
                            )),
                    //  PageViewIndicator(
                    //    isActive: true,
                    //    currentPage: this.currentPage,
                    //    length: weeks.length,
                    // )
                  ],
                )),
          );
        });
  }

  searchSchedule(model) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
      return  StatefulBuilder(
            builder:(context, setState) {
              return
                AlertDialog(
                  title: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        TranslationBase.of(context).search,
                        style: TextStyle(fontSize: 22),
                      ),
                      Text(
                        TranslationBase.of(context).searchFindSchedule,
                        style: TextStyle(fontSize: 16),
                      )
                    ],
                  ),
                  content: Container(
                    height: 150,
                    child: Column(children: [
                      InkWell(
                          onTap: () {
                            DatePicker.showDatePicker(
                              context,
                              showTitleActions: true,
                              minTime: DateTime(DateTime.now().year - 1, 1, 1),
                              maxTime: DateTime.now().add(Duration(days:365)),
                              onConfirm: (date) {
                                setState(() {
                                  fromDate = DateFormat('yyyy-MM-dd').format(date);
                                });
                              },
                            );
                          },
                          child: Container(
                              padding:
                              EdgeInsets.only(top: 5, left: 12, right: 12, bottom: 5),
                              width: double.infinity,
                              height: 55,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                        blurRadius: .26,
                                        spreadRadius: 1 * 1.5,
                                        color: Colors.black.withOpacity(.05))
                                  ]),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).dateFrom,
                                    style: TextStyle(fontSize: 12),
                                  ),
                                  Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(fromDate, style: TextStyle(fontSize: 14),),
                                        Icon(Icons.calendar_month_outlined)
                                      ])
                                ],
                              ))),
                      SizedBox(height: 20,),
                      InkWell(
                          onTap: () {
                            DatePicker.showDatePicker(
                              context,
                              showTitleActions: true,
                              minTime: DateTime(DateTime.now().year - 1, 1, 1),
                               maxTime: DateTime.now().add(Duration(days:365)),
                              onConfirm: (date) {
                                setState(() {
                                  toDate = DateFormat('yyyy-MM-dd').format(date);
                                });
                              },
                            );
                          },
                          child: Container(
                              padding:
                              EdgeInsets.only(top: 5, left: 12, right: 12, bottom: 5),
                              width: double.infinity,
                              height: 56,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                        blurRadius: .26,
                                        spreadRadius: 1 * 1.5,
                                        color: Colors.black.withOpacity(.05))
                                  ]),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).toDate,
                                    style: TextStyle(fontSize: 12),
                                  ),
                                  Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(toDate, style: TextStyle(fontSize: 14),),
                                        Icon(Icons.calendar_month_outlined)
                                      ])
                                ],
                              )))
                    ]),
                  ),
                  actions: [
                    AppButton(
                     title:TranslationBase.of(context).search,
                      onPressed: () {
                       setState((){
                         model.getDoctorRota(fromDate, toDate);
                         Navigator.pop(context);
                       });
                      },
                    )
                  ],
                );
              ;
            }
        );

      },
    );
  }

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