import 'dart:convert';
import 'package:doctor/connected_patients/records_on_click.dart';
import 'package:doctor/models/patient_records_model.dart';
import 'package:flutter/material.dart';
import 'package:doctor/common/settings.dart';
import 'package:intl/intl.dart';

class PatientRecords extends StatefulWidget {
  var patientDetails;
  PatientRecords({this.patientDetails});

  @override
  State<PatientRecords> createState() => _PatientRecordsState();
}

class _PatientRecordsState extends State<PatientRecords> {

  List<PatientRecordsModel> recordsList = [];
  List<PatientRecordsModel> recordsListOriginal = [];
  bool isReportsDataLoading = false;
  bool isDynamicDigitsVisible = false;
  bool isSereverIssue = false;
  TextEditingController searchController = TextEditingController();
  TextEditingController dateInput = TextEditingController();
  TextEditingController fromdateController = TextEditingController();
  TextEditingController todateController = TextEditingController();
  final TextEditingController _fieldOne = TextEditingController();
  final TextEditingController _fieldTwo = TextEditingController();
  final TextEditingController _fieldThree = TextEditingController();
  final TextEditingController _fieldFour = TextEditingController();
  final TextEditingController _fieldFive = TextEditingController();
  final TextEditingController _fieldSix = TextEditingController();
  DateTime fromDate=DateTime.now();
  String dropdownSearchType = 'Problem';
  String? searchBy;
  var typeOfSearchItems = [
    'Problem',
    'Doctor',
    'Date',
  ];
  String? _otp;

  Future<void> getAllRecords() async {
    isReportsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords(widget.patientDetails.customer_id);

      setState(() {
        recordsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PatientRecordsModel.fromJson(model);
        }).toList();
        recordsList=recordsListOriginal.reversed.toList();
        isReportsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isReportsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByProblemName(var problem) async {

    isReportsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords(widget.patientDetails.customer_id);

      setState(() {
        recordsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PatientRecordsModel.fromJson(model);
        }).toList();
        recordsList=recordsListOriginal.reversed.toList();
        recordsList= recordsListOriginal.where(
                (x) => x.problem.toString().toLowerCase().contains(problem.toString().toLowerCase())
        ).toList();
        isReportsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isReportsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByDoctorName(var doctor) async {

    isReportsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords(widget.patientDetails.customer_id);

      setState(() {
        recordsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PatientRecordsModel.fromJson(model);
        }).toList();
        recordsList=recordsListOriginal.reversed.toList();
        recordsList= recordsListOriginal.where(
                (x) => x.doctorName.toString().toLowerCase().contains(doctor.toString().toLowerCase())
        ).toList();
        isReportsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isReportsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByDate(var date) async {

    isReportsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords(widget.patientDetails.customer_id);

      setState(() {
        recordsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PatientRecordsModel.fromJson(model);
        }).toList();
        recordsList=recordsListOriginal.reversed.toList();
        recordsList= recordsListOriginal.where(
                (x) => x.date.toString().toLowerCase().contains(date.toString().toLowerCase())
        ).toList();
        isReportsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isReportsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByDateRange(var fromDate,var toDate) async {
    isReportsDataLoading = true;

    try {
      var response = await AppSettings.getAllRecords(widget.patientDetails.customer_id);

      setState(() {
        recordsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PatientRecordsModel.fromJson(model);
        }).toList();
        recordsList=recordsListOriginal.reversed.toList();
        var dateToCheck = DateTime.now().add(Duration(days: -1));

        recordsList = recordsListOriginal.reversed.where((product) {
          final date = product.dateForFilter;
          final startDate =DateFormat('dd-MM-yyyy').parse(fromDate);
          final endDate = DateFormat('dd-MM-yyyy').parse(toDate);
          return date.isAfter(startDate) && date.isBefore(endDate);

          //reportsList=reportsListOriginal.reversed.toList();
        }).toList();

        /*if( dateToCheck.isAfter(startDate) && dateToCheck.isBefore(endDate))
        {
          print("dateToCheck is between now and lastYear");
        }
        else
        {
          print("dateToCheck is not between now and lastYear");
        }*/


        isReportsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isReportsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  @override
  void initState() {
    getAllRecords();
    var now = new DateTime.now();
    String formattedDate = DateFormat('dd-MM-yyyy').format(now);
    fromdateController.text=formattedDate;
    todateController.text=formattedDate;
    super.initState();
  }

  Widget _filtereddata(){
    if(recordsList.length!=0){
      recordsList.sort((a, b) => b.date.compareTo(a.date));
      return ListView.builder(
          padding:  EdgeInsets.all(0),
          itemCount: recordsList.length,
          itemBuilder: (BuildContext context, int index) {
            if(recordsList[index].patient_type.toLowerCase().toString()=='self'){
              recordsList[index].age=widget.patientDetails.age;
              recordsList[index].patient_name=widget.patientDetails.user_name;
              recordsList[index].gender=widget.patientDetails.gender;

            }

            return GestureDetector(
              onTap: (){

              /*  Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (__) => new AllRecordsOnClick(recordDetails:recordsList[index],initialIndex: 0,))).then((value) {
                  getAllRecords();
                });*/
              },
              child: Card(

                //color: prescriptionsList[index].cardColor,
                child: Padding(
                  padding:EdgeInsets.all(8) ,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: double.infinity,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Problem:',style: problemTextStyle()),
                            Text(recordsList[index].problem.toString().toUpperCase(),style: valuesTextStyle()),
                            Text('Doctor details: ',style: problemTextStyle()),
                            Text(recordsList[index].doctorName.toString().toUpperCase(),style: valuesTextStyle()),
                            Text(recordsList[index].hospitalName.toString().toUpperCase(),style: valuesTextStyle()),
                            Text('Date: ',style: problemTextStyle()),
                            Text(recordsList[index].date.toString().toUpperCase(),style: valuesTextStyle()),
                            Text('Patient details: ',style: problemTextStyle()),
                            Text(recordsList[index].patient_name.toString().toUpperCase(),style: valuesTextStyle()),
                            Row(
                              children: [
                                Text(recordsList[index].gender.toString().toUpperCase(),style: valuesTextStyle()),
                                SizedBox(width:MediaQuery.of(context).size.width * .05,),
                                Text(recordsList[index].age.toString().toUpperCase()+" Yrs",style: valuesTextStyle()),
                              ],
                            ),


                          ],
                        ),


                      ),

                      Visibility(
                        visible:true,
                        child: recordsList[index].isReportVisible?Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: primaryColor, // background
                                onPrimary: Colors.white, // foreground
                              ),
                              onPressed: () async {
                                 Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (__) => new AllRecordsOnClick(recordDetails:recordsList[index],initialIndex: 0,))).then((value) {
                                getAllRecords();
                              });
                              },
                              child:  Text('Findings: '+recordsList[index].findingsImages.length.toString(),style:textButtonStyleReports(),),
                            ),
                            SizedBox(
                              width:MediaQuery.of(context).size.width * .05,
                            ),
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: primaryColor, // background
                                onPrimary: Colors.white, // foreground
                              ),
                              onPressed: () async {
                                Navigator.push(
                                    context,
                                    new MaterialPageRoute(
                                        builder: (__) => new AllRecordsOnClick(recordDetails:recordsList[index],initialIndex: 0,))).then((value) {
                                  getAllRecords();
                                });

                              },
                              child:  Text('Reports: '+recordsList[index].reportImages.length.toString(),style:textButtonStyleReports()),
                            ),
                            SizedBox(
                              width:MediaQuery.of(context).size.width * .05,
                            ),
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: primaryColor, // background
                                onPrimary: Colors.white, // foreground
                              ),
                              onPressed: () async {
                                Navigator.push(
                                    context,
                                    new MaterialPageRoute(
                                        builder: (__) => new AllRecordsOnClick(recordDetails:recordsList[index],initialIndex: 0,))).then((value) {
                                  getAllRecords();
                                });


                              },
                              child:  Text('Prescriptions: '+recordsList[index].prescriptionImages.length.toString(),style:textButtonStyleReports()),
                            ),
                          ],
                        ):Container(
                          child: TextButton(
                            onPressed: () async{
                              var payload = new Map<String, dynamic>();
                              payload["customerId"] = recordsList[index].customerId;
                              payload["doctorId"] =AppSettings.doctorId;
                              payload["recordId"] = recordsList[index].recordId;

                              try{
                                var response = await AppSettings.getDynamicCode(payload);
                                print(jsonDecode(response));
                                setState(() {
                                  recordsList[index].isDynamicDigitsVisible=true;
                                });

                              }
                              catch(e){
                                print(e);
                              }




                            },
                            child: Column(
                              children: [
                                 Visibility(
                                   visible: !recordsList[index].isDynamicDigitsVisible,
                                   child: Text('Click here to request to see patient records',
                                     style: TextStyle(
                                       color: primaryColor,
                                       fontSize: 14,
                                       decoration: TextDecoration.underline,
                                     )),),
                                SizedBox(
                                  height:MediaQuery.of(context).size.height * .02,
                                ),
                                Visibility(
                                  visible:recordsList[index].isDynamicDigitsVisible,
                                  child: Column(
                                    children: [
                                      Text('Please enter 6 digit code provided by the patient',
                                          style: TextStyle(
                                            color: primaryColor,
                                            fontSize: 14,
                                          )),
                                      SizedBox(
                                        height:MediaQuery.of(context).size.height * .02,
                                      ),
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                        children: [
                                          OtpInput(_fieldOne, true), // auto focus
                                          OtpInput(_fieldTwo, false),
                                          OtpInput(_fieldThree, false),
                                          OtpInput(_fieldFour, false),
                                          OtpInput(_fieldFive, false),
                                          OtpInput(_fieldSix, false),
                                        ],
                                      ),
                                      SizedBox(
                                        height:MediaQuery.of(context).size.height * .02,
                                      ),
                                      Container(
                                          width:double.infinity,
                                          height: MediaQuery.of(context).size.height * .06,
                                          child: ElevatedButton(
                                            style: ElevatedButton.styleFrom(
                                              primary: buttonColors, // background
                                              onPrimary: Colors.black, // foreground
                                            ),
                                            onPressed: () async {

                                              setState(() {
                                                _otp = _fieldOne.text +
                                                    _fieldTwo.text +
                                                    _fieldThree.text +
                                                    _fieldFour.text+
                                                    _fieldFive.text +
                                                    _fieldSix.text;
                                              });
                                              if (_otp!.length ==     6) {
                                                AppSettings.preLoaderDialog(context);

                                                bool isOnline = await AppSettings.internetConnectivity();

                                                if(isOnline){
                                                  var payload = new Map<String, dynamic>();
                                                  payload["dynamicCode"] = _otp.toString();
                                                  payload["recordId"] = recordsList[index].recordId;
                                                  payload["customerId"] = recordsList[index].customerId;
                                                  bool codeVerified = await AppSettings.dynamicCodeVerification(payload);
                                                  if(codeVerified){
                                                    Navigator.of(context,rootNavigator: true).pop();
                                                    AppSettings.longSuccessToast("Code verified successfully");
                                                    setState(() {
                                                      recordsList[index].isReportVisible=true;
                                                      recordsList[index].isDynamicDigitsVisible=false;
                                                          _fieldOne.clear();
                                                          _fieldTwo.clear();
                                                          _fieldThree.clear();
                                                          _fieldFour.clear();
                                                          _fieldFive.clear();
                                                          _fieldSix.clear();
                                                    });
                                                    //getAllRecords();
                                                  }
                                                  else{
                                                    Navigator.of(context,rootNavigator: true).pop();
                                                    AppSettings.longFailedToast(
                                                        "please enter valid pin");
                                                    recordsList[index].isReportVisible=false;
                                                    //getAllRecords();
                                                  }


                                                }
                                                else{
                                                  Navigator.of(context,rootNavigator: true).pop();
                                                  AppSettings.longFailedToast(
                                                      "Please check your internet");
                                                }


                                              }
                                              else{

                                              }

                                            },
                                            child: Text('Verify'),
                                          )),
                                    ],
                                  )),
                              ],
                            )
                          ),
                        ),)

                    ],
                  ),
                ),
              ),
            );
          });
    }
    else{
      return   Padding(padding: EdgeInsets.fromLTRB(60,10,60,10),
        child: Column(
          children: [
            Text('No records found related to your search'),
            SizedBox(
              height: 20,
            ),
            CircleAvatar(
              backgroundColor: Colors.red,
              radius: 30,
              child: const Icon(
                Icons.info,
                color: Colors.white,
              ),
            )
          ],
        ),);

    }
  }

  Widget _allreports(){

    if(recordsListOriginal.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            /*Container(
              padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
              child: DropdownButtonFormField(
                // Initial Value
                value: dropdownSearchType,
                isExpanded: true,
                decoration: const InputDecoration(
                  prefixIcon: Icon(
                    Icons.search,
                    color: greyColor,
                  ),
                  border: OutlineInputBorder(
                      borderSide: BorderSide(color: greyColor)),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: greyColor),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: greyColor),
                  ),
                  labelText: 'Search By',
                  labelStyle: TextStyle(
                    color: greyColor, //<-- SEE HERE
                  ),
                ),

                hint: Text('Select Search Type'),
                // Down Arrow Icon
                icon: const Icon(Icons.keyboard_arrow_down),

                // Array list of items
                items: typeOfSearchItems.map((String items) {
                  return DropdownMenuItem(
                    value: items,
                    child: Text(items),
                  );
                }).toList(),
                // After selecting the desired option,it will
                // change button value to selected value
                onChanged: (String? newValue) {
                  setState(() {
                    dropdownSearchType = newValue!;
                  });
                },
              ),
            ),*/
            Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.fromLTRB(10,10,0,0),
                      child: Text('Please select search option',style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold,fontSize: 16),),),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: RadioListTile(
                            title: Text("Problem", style: TextStyle(fontSize: 10)),
                            value: "problem",
                            groupValue: searchBy,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                searchBy = value.toString();
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile(
                            title: Text(
                              "Doctor",
                              style: TextStyle(fontSize: 10),
                            ),
                            value: "doctor",
                            groupValue: searchBy,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                searchBy = value.toString();
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile(
                            title:
                            Text("Date", style: TextStyle(fontSize: 10)),
                            value: "date",
                            groupValue: searchBy,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                searchBy = value.toString();
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ],
                )

            ),
            Visibility(
              visible:searchBy.toString().toLowerCase()=='problem' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByProblemName(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      /*suffixIcon: Icon(
                              Icons.clear,
                              color: greyColor,
                            ),*/
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by problem',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),),
            Visibility(
              visible:searchBy.toString().toLowerCase()=='doctor' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByDoctorName(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      /*suffixIcon: Icon(
                              Icons.clear,
                              color: greyColor,
                            ),*/
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by doctor',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),),
            Visibility(
              visible:searchBy.toString().toLowerCase()=='date',
              child: Container(
                //height: 60,
                padding:  EdgeInsets.all(5),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(

                        cursorColor: primaryColor,
                        controller: fromdateController,
                        onChanged: (string) {
                          if(string.length>=1){
                            //getRecordsByDate(string);
                          }
                          else{
                            getAllRecords();
                          }
                        },
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(1950),
                            lastDate: DateTime.now(),
                            builder: (BuildContext context, Widget? child) {
                              return Theme(
                                data: ThemeData.dark().copyWith(
                                  colorScheme: ColorScheme.dark(
                                    primary: buttonColors,
                                    onPrimary: Colors.white,
                                    surface: buttonColors,
                                    onSurface: Colors.white,
                                  ),
                                  dialogBackgroundColor: primaryColor,
                                ),
                                child: child!,
                              );
                            },
                          );

                          if (pickedDate != null) {
                            print(pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                            String formattedDate = DateFormat('dd-MM-yyyy').format(pickedDate);
                            print(formattedDate); //formatted date output using intl package =>  2021-03-16
                            setState(() {
                              fromDate=pickedDate;
                              fromdateController.text = formattedDate; //set output date to TextField value.
                            });
                            getRecordsByDateRange(fromdateController.text,todateController.text);
                          } else {}
                        },
                        decoration:  InputDecoration(
                          prefixIcon: Icon(
                            Icons.calendar_month,
                            color: primaryColor,
                          ),
                          suffixIcon: fromdateController.text!=''?IconButton(
                            icon:  Icon(
                              Icons.clear,
                              color: Colors.red,
                            ),
                            onPressed: () {
                              setState(() {
                                fromdateController.text='';
                              });
                              getAllRecords();
                            },
                          ):IconButton(
                            icon:  Icon(
                              Icons.clear,
                              color: Colors.transparent,
                            ),
                            onPressed: () {
                            },
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          //labelText: 'Search by phone number',
                          hintText: 'From date',

                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 5),
                    Expanded(
                      child: TextField(

                        cursorColor: primaryColor,
                        controller: todateController,
                        onChanged: (string) {
                          if(string.length>=1){
                            //getRecordsByDate(string);
                          }
                          else{
                            getAllRecords();
                          }
                        },
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: fromDate,
                            lastDate: DateTime.now(),
                            builder: (BuildContext context, Widget? child) {
                              return Theme(
                                data: ThemeData.dark().copyWith(
                                  colorScheme: ColorScheme.dark(
                                    primary: buttonColors,
                                    onPrimary: Colors.white,
                                    surface: buttonColors,
                                    onSurface: Colors.white,
                                  ),
                                  dialogBackgroundColor: primaryColor,
                                ),
                                child: child!,
                              );
                            },
                          );

                          if (pickedDate != null) {
                            print(
                                pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                            String formattedDate =
                            DateFormat('dd-MM-yyyy').format(pickedDate);
                            print(
                                formattedDate); //formatted date output using intl package =>  2021-03-16
                            setState(() {
                              todateController.text = formattedDate; //set output date to TextField value.
                            });
                            getRecordsByDateRange(fromdateController.text,todateController.text);
                          } else {}
                        },
                        decoration:  InputDecoration(
                          prefixIcon: Icon(
                            Icons.calendar_month,
                            color: primaryColor,
                          ),
                          suffixIcon: todateController.text!=''?IconButton(
                            icon:  Icon(
                              Icons.clear,
                              color: Colors.red,
                            ),
                            onPressed: () {
                              setState(() {
                                todateController.text='';
                              });
                              getAllRecords();
                            },
                          ):IconButton(
                            icon:  Icon(
                              Icons.clear,
                              color: Colors.transparent,
                            ),
                            onPressed: () {
                            },
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          //labelText: 'Search by phone number',
                          hintText: 'To date',

                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 5),

                  ],
                ),
              ),),
            /*Visibility(
              visible:searchBy.toString().toLowerCase()=='date' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByDate(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    onTap: () async {
                      DateTime? pickedDate = await showDatePicker(
                        context: context,
                        initialDate: DateTime.now(),
                        firstDate: DateTime(1950),
                        lastDate: DateTime.now(),
                        builder: (BuildContext context, Widget? child) {
                          return Theme(
                            data: ThemeData.dark().copyWith(
                              colorScheme: ColorScheme.dark(
                                primary: buttonColors,
                                onPrimary: Colors.white,
                                surface: buttonColors,
                                onSurface: Colors.white,
                              ),
                              dialogBackgroundColor: primaryColor,
                            ),
                            child: child!,
                          );
                        },
                      );

                      if (pickedDate != null) {
                        print(
                            pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                        String formattedDate =
                        DateFormat('dd-MM-yyyy').format(pickedDate);
                        print(
                            formattedDate); //formatted date output using intl package =>  2021-03-16
                        setState(() {
                          searchController.text = formattedDate; //set output date to TextField value.
                        });
                        getRecordsByDate(searchController.text);
                      } else {}
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by date',

                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),


             ),*/
            Expanded(child: _filtereddata()),

          ]);


    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('No Records found related to selected patient'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.info,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      /*Navigator.push(context, MaterialPageRoute(builder: (context) => AddReports())).then((value) {
                        getAllRecords();
                      });*/
                    },
                  ),
                )
              ],
            ),
          )
      );
    }


  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Records'),
      body: isReportsDataLoading?Center(
        child: CircularProgressIndicator(
          color: primaryColor,
          strokeWidth: 5.0,
        ),
      ): _allreports(),
    );
  }

}

class OtpInput extends StatelessWidget {
  final TextEditingController controller;
  final bool autoFocus;
  const OtpInput(this.controller, this.autoFocus, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 60,
      width: 50,
      child: TextField(
        autofocus: autoFocus,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        controller: controller,
        maxLength: 1,
        cursorColor: Theme.of(context).primaryColor,
        decoration: const InputDecoration(
            filled: true,
            fillColor: Colors.white,
            border: OutlineInputBorder(borderSide: BorderSide(color: primaryColor)),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: primaryColor),
            ),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: primaryColor),
            ),
            counterText: '',
            hintStyle: TextStyle(color: Colors.black, fontSize: 20.0)),
        onChanged: (value) {
          if (value.length == 1) {
            FocusScope.of(context).nextFocus();
          }
        },
      ),
    );
  }
}
