import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientSearchViewModel.dart';
import 'package:doctor_app_flutter/widgets/patients/patient_card/PatientCard.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

import '../../../routes.dart';
import 'NoData.dart';

class ListOfAllInPatient extends StatefulWidget {
  const ListOfAllInPatient({
    Key? key,
    required this.isAllClinic,
    required this.hasQuery,
    required this.patientSearchViewModel,
    required this.isVidaPlusProject,  this.selectedClinicName,this.query, this.isSortDes
  }) : super(key: key);

  final bool isAllClinic;
  final bool hasQuery;
  final bool isVidaPlusProject;
  final bool? isSortDes;
  final String? selectedClinicName;
  final String? query;
  final PatientSearchViewModel patientSearchViewModel;

  @override
  State<ListOfAllInPatient> createState() => _ListOfAllInPatientState();
}

class _ListOfAllInPatientState extends State<ListOfAllInPatient> {
  final ScrollController _scrollController = ScrollController();

 @override
  void initState() {

   // 2. Add a listener to the controller to trigger pagination.
   _scrollController.addListener(() {
     // Check if we are at the end of the list and not currently loading.
     if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 50 &&
         !widget.patientSearchViewModel.paginationLoading) {
       // Trigger the data fetch only if pagination is allowed.

         widget.patientSearchViewModel.paginatedInPatientCall(widget.selectedClinicName,widget.query, widget.isSortDes);

     }
   });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.0),
        child: widget.patientSearchViewModel.filteredInPatientItems.length == 0
            ? NoData()
            : NotificationListener(
                child: ListView.builder(
                    itemCount: widget.patientSearchViewModel.filteredInPatientItems.length,
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    controller : _scrollController,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return PatientCard(
                        patientInfo: widget.patientSearchViewModel.filteredInPatientItems[index],
                        patientType: "1",
                        arrivalType: "1",
                        isInpatient: true,
                        isMyPatient: widget.patientSearchViewModel.filteredInPatientItems[index].doctorId == widget.patientSearchViewModel.doctorProfile!.doctorID,
                        onTap: () {
                          FocusScopeNode currentFocus = FocusScope.of(context);
                          if (!currentFocus.hasPrimaryFocus) {
                            currentFocus.unfocus();
                          }

                          SchedulerBinding.instance.addPostFrameCallback((_) {
                            Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
                              "patient": widget.patientSearchViewModel.filteredInPatientItems[index],
                              "patientType": "1",
                              "from": "0",
                              "to": "0",
                              "isSearch": false,
                              "isInpatient": true,
                              "arrivalType": "1",
                              "isMyPatient": widget.patientSearchViewModel.filteredInPatientItems[index].doctorId == widget.patientSearchViewModel.doctorProfile!.doctorID,
                              "isVidaPlusProject": widget.isVidaPlusProject,
                            });
                          });
                        },
                      );
                    }),
                onNotification: (notification) {
                  if (widget.isAllClinic && !widget.hasQuery) if (notification is ScrollUpdateNotification) {
                    if (notification.metrics.pixels >= notification.metrics.maxScrollExtent - 50) {
                      widget.patientSearchViewModel.addOnFilteredList();
                    }

                    if (notification.metrics.pixels <= notification.metrics.minScrollExtent - 50) {
                      widget.patientSearchViewModel.removeOnFilteredList();
                    }
                  }
                  return false;
                },
              ),
      ),
    );
  }
}
