import 'dart:collection';

import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/laser_body_parts.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/laser_body_parts_data.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LaserClinic extends StatefulWidget {
  LaserClinic({Key key}) : super(key: key);

  @override
  _LaserClinicState createState() {
    return _LaserClinicState();
  }
}

class _LaserClinicState extends State<LaserClinic> with SingleTickerProviderStateMixin {
  List<int> _laserCategoryList = [1, 2, 11];
  List<LaserBodyPart> _selectedBodyPartList = [];
  bool _isFullBody = false;
  LaserBodyPart fullBody;
  int _selectedCategoryIndex = 0;
  List<LaserBodyPart> laserBodyPartsList = [];

  TabController _tabController;
  int _duration = 0;

  List<LaserCategoryType> maleLaserCategory = [];
  List<LaserCategoryType> femaleLaserCategory = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
      } else {
        _selectedBodyPartList = List<LaserBodyPart>();
        laserBodyPartsList = List<LaserBodyPart>();
        _selectedCategoryIndex = 0;
        setState(() {});
        if (_tabController.index == 0) {
          callLaserBodyPartsAPI(maleLaserCategory[_selectedCategoryIndex].laserCategoryID);
        } else {
          callLaserBodyPartsAPI(femaleLaserCategory[_selectedCategoryIndex].laserCategoryID);
        }
      }
    });
    Future.delayed(Duration.zero, () {
      callLaserBodyPartsAPI(maleLaserCategory[_selectedCategoryIndex].laserCategoryID);
    });
  }

  callLaserBodyPartsAPI(int laserCategoryId) async {
    GifLoaderDialogUtils.showMyDialog(context);

    DoctorsListService service = new DoctorsListService();
    service.getLaserBodyPartsList(laserCategoryId).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        if (res['Laser_GetBodyPartsByCategoryList'].length != 0) {
          List<LaserBodyPart> _tempList = List<LaserBodyPart>();
          res['Laser_GetBodyPartsByCategoryList'].forEach((v) {
            _tempList.add(LaserBodyPart.fromJson(v));
          });
          if (_tempList[0].category == 1 || _tempList[0].category == 11 || _tempList[0].category == 2 || _tempList[0].category == 10) {
            fullBody = _tempList[0];
            _tempList.removeAt(0);
          }
          laserBodyPartsList = _tempList;
        } else {}
        setState(() {});
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
  }

  bool lastIndexIsFirst = false;
  bool isLastIndexIsBack = false;
  ProjectViewModel projectViewModel;

  bool get isMale => _tabController.index == 0;

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    maleLaserCategory = [
      LaserCategoryType(1, TranslationBase.of(context).bodyString),
      LaserCategoryType(2, TranslationBase.of(context).face),
      LaserCategoryType(11, TranslationBase.of(context).retouch),
    ];
    femaleLaserCategory = [
      LaserCategoryType(1, TranslationBase.of(context).bodyString),
      LaserCategoryType(2, TranslationBase.of(context).face),
      LaserCategoryType(10, TranslationBase.of(context).bikini),
      LaserCategoryType(11, TranslationBase.of(context).retouch),
    ];
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).laserClinic,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      isShowDecPage: false,
      backgroundColor: Color(0xfff7f7f7),
      body: Column(
        children: [
          TabBar(
            controller: _tabController,
            indicatorWeight: 3.0,
            indicatorSize: TabBarIndicatorSize.tab,
            labelColor: Color(0xff2B353E),
            unselectedLabelColor: Color(0xff575757),
            labelPadding: EdgeInsets.only(top: 15, bottom: 13, left: 20, right: 20),
            labelStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              letterSpacing: -0.48,
            ),
            unselectedLabelStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              fontFamily: projectViewModel.isArabic ? 'Cairo' : 'Poppins',
              letterSpacing: -0.48,
            ),
            tabs: [Text(TranslationBase.of(context).male), Text(TranslationBase.of(context).female)],
          ),
          Expanded(
            child: TabBarView(
              physics: BouncingScrollPhysics(),
              controller: _tabController,
              children: <Widget>[male(), female()],
            ),
          ),
          Row(
            children: [
              Expanded(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      TranslationBase.of(context).totalMinutes + ":",
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: Color(0xff575757),
                        letterSpacing: -0.48,
                      ),
                    ),
                    Text(
                      "${getDuration()} / 90",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Color(0xff2E303A),
                        letterSpacing: -0.64,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: DefaultButton(
                  TranslationBase.of(context).continues,
                  getDuration() != 0 ? () {
                    callDoctorsSearchAPI();
                  } : null,
                  color: CustomColors.green,
                  disabledColor: CustomColors.grey2,
                ),
              ),
            ],
          ).insideContainer,
        ],
      ),
    );
  }

  callDoctorsSearchAPI() {
    GifLoaderDialogUtils.showMyDialog(context);
    List<DoctorList> doctorsList = [];
    List<String> arr = [];
    List<String> arrDistance = [];
    List<String> result;
    int numAll;
    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = List();

    DoctorsListService service = new DoctorsListService();
    service.getDoctorsList(253, 0, false, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorList'].length != 0) {
            doctorsList.clear();
            res['DoctorList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
            });
            doctorsList.forEach((element) {
              List<PatientDoctorAppointmentList> doctorByHospital = _patientDoctorAppointmentListHospital
                  .where(
                    (elementClinic) => elementClinic.filterName == element.projectName,
                  )
                  .toList();

              if (doctorByHospital.length != 0) {
                _patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList.add(element);
              } else {
                _patientDoctorAppointmentListHospital
                    .add(PatientDoctorAppointmentList(filterName: element.projectName, distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element));
              }
            });
          } else {}
        });

        result = LinkedHashSet<String>.from(arr).toList();
        numAll = result.length;
        navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
  }

  Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async {
    Navigator.push(context, FadePage(page: SearchResults(isLiveCareAppointment: false, doctorsList: docList, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital)))
        .then((value) {
      setState(() {
        // dropdownValue = null;
      });
      // getProjectsList();
    });
  }

  int getDuration() {
    int duration = 0;
    if (_isFullBody) {
      _duration = int.parse(fullBody.timeDuration);
      return _duration;
    }

    var lowerUpperLegsList = _selectedBodyPartList.where((element) => element.mappingCode == "47" || element.mappingCode == "48")?.toList() ?? [];
    var upperLowerArmsList = _selectedBodyPartList.where((element) => element.mappingCode == "40" || element.mappingCode == "41")?.toList() ?? [];

    if (_selectedBodyPartList.length > 0) {
      duration = _selectedBodyPartList.fold(0, (previousValue, element) => previousValue + int.parse(element.timeDuration));
    }
    print("duration:$duration");
    if (lowerUpperLegsList.length == 2) {
      duration -= 30;
    }
    print("duration1:$duration");
    if (upperLowerArmsList.length == 2) {
      duration -= 15;
    }
    print("duration2:$duration");
    // for (int i = 0; i < _selectedBodyPartList.length; i++) {
    //   if (
    //
    //   (lowerUpperLegsList.length == 2 && (_selectedBodyPartList[i].mappingCode == "47" || _selectedBodyPartList[i].mappingCode == "48")) ||
    //       (upperLowerArmsList.length == 2 && (_selectedBodyPartList[i].mappingCode == "40" || _selectedBodyPartList[i].mappingCode == "41"))
    //
    //
    //   ) {
    //     print("duration:$duration");
    //
    //     duration += 15;
    //     print("duration1:$duration");
    //   } else {
    //     duration += int.parse(_selectedBodyPartList[i].timeDuration);
    //   }
    // }
    print(duration);
    _duration = duration;
    return duration;
  }

  Widget laserCategoryWidget(List<LaserCategoryType> list, VoidCallback onTap) {
    return SizedBox(
      height: 40,
      child: ListView.separated(
        itemCount: list.length,
        physics: BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        separatorBuilder: (cxt, index) => SizedBox(width: 8),
        itemBuilder: (cxt, index) {
          return InkWell(
            onTap: () {
              //   setState(() {
              _selectedCategoryIndex = index;
              //     });
              onTap();
            },
            child: Container(
              decoration: BoxDecoration(
                color: _selectedCategoryIndex == index ? Color(0xffD02127) : Colors.white,
                borderRadius: BorderRadius.circular(36),
                border: Border.all(
                  width: 1,
                  color: _selectedCategoryIndex == index ? Colors.transparent : Color(0xffEAEAEA),
                ),
              ),
              padding: EdgeInsets.symmetric(vertical: 8, horizontal: 26),
              child: Text(
                list[index].title,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: _selectedCategoryIndex == index ? Colors.white : Color(0xff535353),
                  letterSpacing: -0.48,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget bodyPartsGridView() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 21, horizontal: 14),
      margin: EdgeInsets.only(top: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(
          Radius.circular(15.0),
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xff000000).withOpacity(.05),
            blurRadius: 27,
            offset: Offset(0, -3),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (fullBody != null)
            Row(
              children: [
                SizedBox(
                  width: 22,
                  height: 22,
                  child: Theme(
                    data: Theme.of(context).copyWith(
                      unselectedWidgetColor: Color(0xffEAEAEA),
                    ),
                    child: Checkbox(
                      value: _isFullBody,
                      onChanged: (value) {
                        setState(() {
                          if (value) {
                            _selectedBodyPartList.clear();
                          }
                          _isFullBody = !_isFullBody;
                        });
                      },
                      activeColor: Color(0xffD02127),
                    ),
                  ),
                ),
                SizedBox(width: 12),
                Text(
                  projectViewModel.isArabic ? fullBody.bodyPartN : fullBody.bodyPart,
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.6, height: 21 / 14),
                ),
              ],
            ),
          GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 85 / 107, crossAxisSpacing: 4, mainAxisSpacing: 21),
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: laserBodyPartsList.length,
            padding: fullBody != null ? EdgeInsets.only(top: 16) : EdgeInsets.zero,
            itemBuilder: (BuildContext context, int index) {
              bool _isSelected = _selectedBodyPartList.any((file) => file.id == laserBodyPartsList[index].id);
              return InkWell(
                onTap: _isFullBody
                    ? null
                    : () {
                        if (_duration >= 90) {
                          if (_isSelected) {
                            _selectedBodyPartList.removeWhere((element) => element.id == laserBodyPartsList[index].id);

                            //  _selectedBodyPartList.remove(laserBodyPartsList[index]);
                            setState(() {});
                            return;
                          }
                          AppToast.showToast(message: TranslationBase.of(context).laserMaxLimitReach);
                          return;
                        }
                        if (_isSelected) {
                          _selectedBodyPartList.removeWhere((element) => element.id == laserBodyPartsList[index].id);
                          //   _selectedBodyPartList.remove(laserBodyPartsList[index]);
                        } else {
                          if (_duration + int.parse(laserBodyPartsList[index].timeDuration) > 90) {
                            AppToast.showToast(message: TranslationBase.of(context).laserMaxLimitReach);
                            return;
                          }
                          _selectedBodyPartList.add(laserBodyPartsList[index]);
                        }
                        setState(() {});
                      },
                child: AnimatedOpacity(
                  opacity: _isFullBody ? 0.25 : 1.0,
                  duration: Duration(milliseconds: 200),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AspectRatio(
                        aspectRatio: 97 / 97,
                        child: FittedBox(
                          fit: BoxFit.fitWidth,
                          child: Stack(
                            alignment: Alignment.topRight,
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 5, right: 5),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15.0),
                                  border: Border.all(color: _isSelected ? Color(0xffD02127) : Color(0xffEAEAEA), width: 2),
                                ),
                                child: LaserBodyParts()
                                    .getCategoryImage(isMale, (isMale ? maleLaserCategory : femaleLaserCategory)[_selectedCategoryIndex].laserCategoryID, laserBodyPartsList[index].mappingCode),
                              ),
                              if (_isSelected)
                                Container(
                                  width: 18,
                                  height: 18,
                                  child: Icon(Icons.done, color: Colors.white, size: 12),
                                  decoration: BoxDecoration(
                                    color: Color(0xffD02127),
                                    borderRadius: BorderRadius.circular(30.0),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 6),
                      Expanded(
                        child: Text(
                          projectViewModel.isArabic ? laserBodyPartsList[index].bodyPartN : laserBodyPartsList[index].bodyPart,
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            color: Color(0xff2B353E),
                            letterSpacing: -0.48,
                          ),
                          maxLines: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget male() {
    return ListView(
      physics: BouncingScrollPhysics(),
      padding: EdgeInsets.all(21),
      children: [
        laserCategoryWidget(maleLaserCategory, () {
          callLaserBodyPartsAPI(maleLaserCategory[_selectedCategoryIndex].laserCategoryID);
        }),
        if (laserBodyPartsList.isNotEmpty) bodyPartsGridView()
      ],
    );
  }

  Widget female() {
    return ListView(
      physics: BouncingScrollPhysics(),
      padding: EdgeInsets.all(21),
      children: [
        laserCategoryWidget(femaleLaserCategory, () {
          callLaserBodyPartsAPI(femaleLaserCategory[_selectedCategoryIndex].laserCategoryID);
        }),
        if (laserBodyPartsList.isNotEmpty) bodyPartsGridView()
      ],
    );
  }
}

class LaserCategoryType {
  int laserCategoryID;
  String title;

  LaserCategoryType(this.laserCategoryID, this.title);
}
