import 'package:doctor_app_flutter/core/enum/filter_type.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/patient_muse/PatientSearchRequestModel.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientSearchViewModel.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../../../config/config.dart';

class FilterDatePage extends StatefulWidget {
  final PatientSearchViewModel patientSearchViewModel;

  const FilterDatePage({Key? key, required this.patientSearchViewModel})
      : super(key: key);

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

class _FilterDatePageState extends State<FilterDatePage> {
  bool showResetButton = false;

  @override
  void initState() {

    setState(() {
      showResetButton = widget.patientSearchViewModel
          .selectedFromDate != null;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var screenSize;
    return AppScaffold(
        isShowAppBar: false,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        body: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height * 1.0,
            child: Padding(
              padding: EdgeInsets.all(0.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  BottomSheetTitle(
                    title: TranslationBase.of(context).filterInPatient,
                    onCrossClicked: (){
                      if(showResetButton == false){
                        widget.patientSearchViewModel
                            .selectedFromDate = null;
                        widget.patientSearchViewModel
                            .selectedToDate = null;
                      }
                    },
                  ),
                  SizedBox(
                    height: 10.0,
                  ),
                  Center(
                    child: FractionallySizedBox(
                      widthFactor: 0.9,
                      child: Column(
                        children: [
                          Container(
                            color: Colors.white,
                            child: InkWell(
                              onTap: () => selectDate(context,
                                  firstDate: getFirstDate(),
                                  lastDate: getLastDate()),
                              child: TextField(
                                decoration: textFieldSelectorDecoration(
                                    TranslationBase.of(context).fromDate,
                                    widget.patientSearchViewModel
                                                .selectedFromDate !=
                                            null
                                        ? "${AppDateUtils.convertStringToDateFormat(widget.patientSearchViewModel.selectedFromDate.toString(), "yyyy-MM-dd")}"
                                        : "",
                                    true,
                                    suffixIcon: Icon(
                                      Icons.calendar_today,
                                      color: Colors.black,
                                    )),
                                enabled: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            color: Colors.white,
                            child: InkWell(
                              onTap: () => selectDate(context,
                                  isFromDate: false,
                                  firstDate: getFirstDate(),
                                  lastDate: getLastDate()),
                              child: TextField(
                                decoration: textFieldSelectorDecoration(
                                    TranslationBase.of(context).toDate,
                                    widget.patientSearchViewModel
                                                .selectedToDate !=
                                            null
                                        ? "${AppDateUtils.convertStringToDateFormat(widget.patientSearchViewModel.selectedToDate.toString(), "yyyy-MM-dd")}"
                                        : "",
                                    true,
                                    suffixIcon: Icon(
                                      Icons.calendar_today,
                                      color: Colors.black,
                                    )),
                                enabled: false,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        bottomSheet: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(0.0),
            ),
            border: Border.all(color: HexColor('#707070'), width: 0),
          ),
          height: MediaQuery.of(context).size.height * 0.1,
          width: double.infinity,
          child: Column(
            children: [
              SizedBox(
                height: 10,
              ),
              Row(
                children: [
                  Expanded(
                    child: Container(
                      child: FractionallySizedBox(
                        widthFactor: .80,
                        child: Center(
                          child: AppButton(
                            title: TranslationBase.of(context).search,
                            padding: 10,
                            color: AppGlobal.appGreenColor,
                            onPressed: () async {
                              if (widget.patientSearchViewModel.selectedFromDate ==
                                      null ||
                                  widget.patientSearchViewModel.selectedToDate ==
                                      null) {
                                Utils.showErrorToast(
                                    "Please Select All The date Fields ");
                              } else {
                                Navigator.pop(context);
                                await widget.patientSearchViewModel.getInPatientList(
                                    PatientSearchRequestModel(
                                        from:
                                            "${AppDateUtils.convertDateToFormat(widget.patientSearchViewModel.selectedFromDate!, "yyyy-MM-dd")} 00:00:00",
                                        to: "${AppDateUtils.convertDateToFormat(widget.patientSearchViewModel.selectedToDate!, "yyyy-MM-dd")} 00:00:00",
                                        searchType: null)..transformDataForVidaPlus(),
                                    isForceFullRefresh: true, isVidaPlusProject: true);
                              }
                            },
                          ),
                        ),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: showResetButton,
                    child: Expanded(
                      child: Container(
                      child: FractionallySizedBox(
                        widthFactor: .80,
                        child: Center(
                          child: AppButton(
                            title: TranslationBase.of(context).reset,
                            padding: 10,
                            color: AppGlobal.appRedColor,
                            onPressed: () async {
                              this.widget.patientSearchViewModel.selectedToDate = null;
                              this.widget.patientSearchViewModel.selectedFromDate = null;

                              PatientSearchRequestModel requestModel = PatientSearchRequestModel();
                              DateTime dateTime = DateTime.now();
                              String currentDate = AppDateUtils.convertDateToFormat(
                                  dateTime,
                                  'yyyy-MM-dd');
                              print("the current date is $currentDate");
                              requestModel.from = "$currentDate 00:00:00";

                              dateTime = dateTime.add(Duration(days: 1));
                              currentDate = AppDateUtils.convertDateToFormat(
                                  dateTime,
                                  'yyyy-MM-dd');
                              requestModel.to = "$currentDate 00:00:00";
                              requestModel.pageSize = 10;
                              requestModel.pageIndex = 0;
                              requestModel.searchType = null;
                              requestModel.transformDataForVidaPlus();
                              Navigator.pop(context);
                              await widget.patientSearchViewModel.getInPatientList(
                                  requestModel,
                                  isForceFullRefresh: true,isVidaPlusProject: true);
                            },
                          ),
                        ),
                      ),
                    ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 5,
              ),
            ],
          ),
        ));
  }

  selectDate(BuildContext context,
      {bool isFromDate = true, DateTime? firstDate, lastDate}) async {
    Utils.hideKeyboard(context);
    DateTime currentDate = DateTime.now();
    DateTime? selectedDate = isFromDate
        ? this.widget.patientSearchViewModel.selectedFromDate ?? currentDate
        : this.widget.patientSearchViewModel.selectedToDate ?? currentDate;
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: firstDate!,
      lastDate: lastDate,
      initialEntryMode: DatePickerEntryMode.calendar,
    );
    if (picked != null) {
      if (isFromDate) {
        setState(() {
          this.widget.patientSearchViewModel.selectedFromDate = picked;
          var date = picked.add(Duration(days: 30));
          if (date.isBefore(lastDate)) {
            this.widget.patientSearchViewModel.selectedToDate = date;
          } else
            this.widget.patientSearchViewModel.selectedToDate = lastDate;
        });
      } else {
        setState(() {
          this.widget.patientSearchViewModel.selectedToDate = picked;
        });
      }
    }
  }

  getFirstDate() {
    DateTime dateTime = DateTime.now().subtract(Duration(days: 30 * 24));
    return DateTime(dateTime.year, dateTime.month, dateTime.day + 1);
  }

  getLastDate() {
    DateTime dateTime = DateTime.now().add(Duration(days: 30 * 24));
    return DateTime(dateTime.year, dateTime.month, dateTime.day);
  }

  InputDecoration textFieldSelectorDecoration(
      String hintText, String selectedText, bool isDropDown,
      {Icon? suffixIcon}) {
    return InputDecoration(
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFEFEFEF), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFEFEFEF), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown
          ? suffixIcon != null
              ? suffixIcon
              : Icon(
                  Icons.keyboard_arrow_down_sharp,
                  color: Color(0xff2E303A),
                )
          : null,
      hintStyle: TextStyle(
        fontSize: 13,
        color: Color(0xff2E303A),
        fontFamily: 'Poppins',
        fontWeight: FontWeight.w600,
      ),
      labelText: selectedText != null ? '$hintText\n$selectedText' : null,
      labelStyle: TextStyle(
        fontSize: 13,
        color: Color(0xff2E303A),
        fontFamily: 'Poppins',
        fontWeight: FontWeight.w600,
      ),
    );
  }
}
