import 'package:auto_size_text/auto_size_text.dart';
import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/config/config.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/Authentication/select_device_imei_res.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/AppointmentDetails.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart' as auth;
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_new.dart';
import 'package:diplomaticquarterapp/widgets/avatar/large_avatar.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class TimeLineView extends StatefulWidget {
  bool isLogged, isArabic;
  List<AppoitmentAllHistoryResultList> appoitmentAllHistoryResultList;

  TimeLineView(this.isLogged, this.isArabic, this.appoitmentAllHistoryResultList);

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

class _TimeLineViewState extends State<TimeLineView> {
  List<AppoitmentAllHistoryResultList> tempList = [];
  List<DateObj> dateObjs = [];
  DateObj selectedDateObj = null;
  final authService = new auth.AuthProvider();

  @override
  void initState() {
    super.initState();
    dateObjs.add(new DateObj(0, 0, widget.isArabic ? "الكل" : "All"));
    for (int i = 0; i < widget.appoitmentAllHistoryResultList.length; i++) {
      tempList.add(widget.appoitmentAllHistoryResultList[i]);
      dateObjs.add(new DateObj(
          DateUtil.convertStringToDate(widget.appoitmentAllHistoryResultList[i].appointmentDate).month,
          DateUtil.convertStringToDate(widget.appoitmentAllHistoryResultList[i].appointmentDate).year,
          DateUtil.getMonthYearLangDateFormatted(
            DateUtil.convertStringToDate(widget.appoitmentAllHistoryResultList[i].appointmentDate),
            widget.isArabic ? "ar" : "en",
          )));
    }
    dateObjs = dateObjs.toSet().toList();
    dateObjs.sort((a, b) => a.month.compareTo(b.month));
    dateObjs.sort((a, b) => a.year.compareTo(b.year));

    // for (int i = 0; i < dateObjs.length; i++) {
    //   print(dateObjs[i].monthYear.toString());
    // }
  }

  applyFilter(bool isAll) {
    tempList.clear();
    if (isAll) {
      for (int i = 0; i < widget.appoitmentAllHistoryResultList.length; i++) {
        tempList.add(widget.appoitmentAllHistoryResultList[i]);
      }
    } else {
      for (int i = 0; i < widget.appoitmentAllHistoryResultList.length; i++) {
        if (DateUtil.getMonthYearLangDateFormatted(
              DateUtil.convertStringToDate(widget.appoitmentAllHistoryResultList[i].appointmentDate),
              widget.isArabic ? "ar" : "en",
            ) ==
            selectedDateObj.monthYear) {
          tempList.add(widget.appoitmentAllHistoryResultList[i]);
        }
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 210,
      decoration: containerBottomRightRadiusWithGradientBorder(0, darkColor: Color(0xFFF2B353E), lightColor: Color(0xFFF2B353E)),
      child: widget.isLogged && tempList.length > 0
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                mFlex(2),
                Padding(
                  padding: EdgeInsets.only(left: 12, right: 12),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              TranslationBase.of(context).appointments,
                              style: TextStyle(
                                color: CustomColors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                letterSpacing: -0.72,
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).timeLine,
                              style: TextStyle(
                                color: CustomColors.white,
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                letterSpacing: -1.44,
                                height: 1.2,
                              ),
                            ),
                          ],
                        ),
                      ),
                      widget.isLogged
                          ? Container(
                              decoration: containerRadius(Color(0xFF2B2E31), 100),
                              height: 30,
                              child: DropdownButtonHideUnderline(
                                child: ButtonTheme(
                                  alignedDropdown: true,
                                  child: DropdownButton<DateObj>(
                                    hint: Text(
                                      TranslationBase.of(context).all,
                                      style: TextStyle(color: CustomColors.grey2, fontSize: 10),
                                    ),
                                    iconEnabledColor: CustomColors.grey2,
                                    style: TextStyle(color: CustomColors.grey2, fontSize: 10),
                                    dropdownColor: Color(0xFF2B2E31),
                                    value: selectedDateObj,
                                    items: dateObjs.map((DateObj value) {
                                      return DropdownMenuItem<DateObj>(
                                        value: value,
                                        child: new AutoSizeText(
                                          value.monthYear,
                                        ),
                                      );
                                    }).toList(),
                                    onChanged: (r) {
                                      selectedDateObj = r;
                                      applyFilter(r.year == 0 ? true : false);
                                      setState(() {});
                                    },
                                    underline: Container(
                                      height: 0,
                                    ),
                                  ),
                                ),
                              ),
                            )
                          : Container()
                    ],
                  ),
                ),
                mFlex(1),
                widget.isLogged
                    ? Container(
                        height: widget.isArabic ? 130 : 110,
                        width: double.infinity,
                        child: ListView.separated(
                          itemBuilder: (context, index) => Padding(
                            padding: widget.isArabic
                                ? EdgeInsets.only(left: index == 0 ? 0 : 12, right: (tempList.length - 1) == index ? 0 : 12)
                                : EdgeInsets.only(left: index == 0 ? 12 : 0, right: (tempList.length - 1) == index ? 12 : 0),
                            child: TimelineNewWidget(
                              appoitmentAllHistoryResul: tempList[index],
                              isLast: tempList.length - 1 == index ? true : false,
                            ),
                          ),
                          itemCount: tempList.length,
                          scrollDirection: Axis.horizontal,
                          shrinkWrap: false,
                          physics: BouncingScrollPhysics(),
                          separatorBuilder: (BuildContext context, int index) {
                            return mWidth(8);
                          },
                        ),
                      )
                    : Container(),
              ],
            )
          : emptyView(widget.isLogged),
    );
  }

  Widget emptyView(bool isLogged) {
    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: Row(
        children: [
          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                mFlex(2),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      TranslationBase.of(context).appointments,
                      style: TextStyle(
                        color: CustomColors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.72,
                      ),
                    ),
                    Text(
                      TranslationBase.of(context).timeLine,
                      style: TextStyle(
                        color: CustomColors.white,
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -1.44,
                        height: 1.2,
                      ),
                    ),
                  ],
                ),
                mFlex(1),
                Text(
                  isLogged ? TranslationBase.of(context).noAppointmentAvailable : TranslationBase.of(context).cantSeeProfile,
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                    letterSpacing: -0.42,
                  ),
                ),
                mHeight(4),
                !isLogged
                    ? Container(
                        height: MediaQuery.of(context).size.width / 14,
                        width: MediaQuery.of(context).size.width / (widget.isArabic ? 4 : 6),
                        child: CustomTextButton(
                            shape: cardRadiusNew(8),
                            elevation: 0,
                            backgroundColor: Color(0xFFFBF2E31),
                          onPressed: () {
                            // onLoginClick();
                            login();
                          },
                          child: Center(
                            child: AutoSizeText(
                              TranslationBase.of(context).login,
                              maxLines: 1,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                letterSpacing: -0.33,
                                height: 1,
                              ),
                            ),
                          ),
                        ),
                      )
                    : Container(
                        height: MediaQuery.of(context).size.width / 14,
                      ),
                mFlex(3),
              ],
            ),
          ),
          SvgPicture.asset("assets/images/new/empty.svg"),
          mWidth(20),
        ],
      ),
    );
  }

  login() async {
    var data = await sharedPref.getObject(IMEI_USER_DATA);
    sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);
    if (data != null) {
      Navigator.of(context).pushNamed(CONFIRM_LOGIN);
    } else {
      GifLoaderDialogUtils.showMyDialog(context);
      authService.selectDeviceImei(DEVICE_TOKEN).then((SelectDeviceIMEIRES value) {
        GifLoaderDialogUtils.hideDialog(context);
        if (value != null) {
          sharedPref.setObject(IMEI_USER_DATA, value);
          Navigator.of(context).pushNamed(CONFIRM_LOGIN);
        } else {
          Navigator.of(context).pushNamed(
            WELCOME_LOGIN,
          );
        }
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.of(context).pushNamed(
          WELCOME_LOGIN,
        );
      });
    }
  }
}

class TimelineNewWidget extends StatelessWidget {
  bool isLast;
  final AppoitmentAllHistoryResultList appoitmentAllHistoryResul;

  TimelineNewWidget({Key key, this.appoitmentAllHistoryResul, this.isLast});

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return Container(
      width: MediaQuery.of(context).size.width / 2.3,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: double.infinity,
            child: Row(
              children: [
                Text(
                  DateUtil.getDayMonthYearLangDateFormatted(
                    DateUtil.convertStringToDate(appoitmentAllHistoryResul.appointmentDate),
                    projectViewModel.isArabic ? "ar" : "en",
                  ),
                  style: TextStyle(
                    color: Colors.grey[200],
                    fontSize: 12,
                    height: 1.2,
                  ),
                ),
                mWidth(8),
                isLast ? Container() : barView(),
              ],
            ),
          ),
          mHeight(10),
          LargeAvatar(
            onTap: () {
              GAnalytics.APPOINTMENT_DETAIL_FLOW_TYPE = 'timeline';
              Navigator.push(
                  context,
                  FadePage(
                      page: AppointmentDetails(
                    appo: appoitmentAllHistoryResul,
                    parentIndex: 2,
                  )));
            },
            name: appoitmentAllHistoryResul.doctorNameObj,
            disableProfileView: false,
            url: appoitmentAllHistoryResul.doctorImageURL,
            width: 30,
            height: 30,
            isAppointmentAvatar: true,
          ),
          mHeight(6),
          Text(
            appoitmentAllHistoryResul.doctorNameObj,
            style: TextStyle(
              color: CustomColors.white,
              fontSize: 10,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.36,
            ),
          ),
          Text(
            appoitmentAllHistoryResul.clinicName,
            style: TextStyle(
              color: CustomColors.grey2,
              fontSize: 10,
              fontWeight: FontWeight.w600,
              letterSpacing: -0.36,
            ),
          ),
        ],
      ),
    );
  }

  Widget barView() {
    return Flexible(
      child: Container(
        width: double.infinity,
        child: Row(
          children: [
            Container(
              width: 6,
              height: 6,
              decoration: containerColorRadiusBorderWidth(CustomColors.pharmacyGreyColor, 50, CustomColors.grey2, 1),
            ),
            Expanded(
              child: Container(
                width: double.infinity,
                height: 1,
                color: CustomColors.grey2,
              ),
            ),
            Container(
              width: 6,
              height: 6,
              decoration: containerColorRadiusBorderWidth(CustomColors.pharmacyGreyColor, 50, CustomColors.grey2, 1),
            ),
          ],
        ),
      ),
    );
  }
}

// ignore: must_be_immutable
class DateObj extends Equatable {
  int month;
  int year;
  String monthYear;

  DateObj(this.month, this.year, this.monthYear);

  @override
  List<Object> get props => [monthYear];
}
