import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_clinic_list_response_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/get_livecare_clinics_response_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/models/resp_models/get_livecare_immediate_clinics_response_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_payment_details.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/clinic_card.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/widgets/livecare_clinic_card.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class SelectImmediateLiveCareClinicPage extends StatefulWidget {
  const SelectImmediateLiveCareClinicPage({super.key});

  @override
  State<SelectImmediateLiveCareClinicPage> createState() => _SelectImmediateLiveCareClinicPageState();
}

class _SelectImmediateLiveCareClinicPageState extends State<SelectImmediateLiveCareClinicPage> {
  TextEditingController searchEditingController = TextEditingController();
  FocusNode textFocusNode = FocusNode();
  late AppState appState;
  late ImmediateLiveCareViewModel immediateLiveCareViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      immediateLiveCareViewModel.getLiveCareImmediateClinicsList();
      immediateLiveCareViewModel.setLiveCareSelectedCallType(0);
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    immediateLiveCareViewModel = Provider.of<ImmediateLiveCareViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.selectLiveCareClinic.tr(),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(24.h),
            child: Consumer<ImmediateLiveCareViewModel>(builder: (context, immediateLiveCareVM, child) {
              return Column(
                children: [
                  TextInputWidget(
                    labelText: LocaleKeys.search.tr(context: context),
                    hintText: LocaleKeys.clinicName.tr(context: context),
                    controller: searchEditingController,
                    isEnable: true,
                    prefix: null,
                    autoFocus: false,
                    isBorderAllowed: false,
                    keyboardType: TextInputType.text,
                    focusNode: textFocusNode,
                    suffix: searchEditingController.text.isNotEmpty
                        ? GestureDetector(
                      onTap: () {
                        searchEditingController.clear();
                        immediateLiveCareVM.filterClinic("");
                        textFocusNode.unfocus();
                      },
                      child: Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown),
                    )
                        : null,
                    onChange: (value) {
                      immediateLiveCareVM.filterClinic(value!);
                    },
                    padding: EdgeInsets.symmetric(
                      vertical: ResponsiveExtension(10).h,
                      horizontal: ResponsiveExtension(15).h,
                    ),
                  ),
                  ListView.separated(
                    padding: EdgeInsets.only(top: 16.h),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: immediateLiveCareVM.isImmediateLiveCareClinicsLoading ? 5 : immediateLiveCareVM.immediateLiveCareClinicsList.length,
                    itemBuilder: (context, index) {
                      return immediateLiveCareVM.isImmediateLiveCareClinicsLoading
                          ? ClinicCard(
                              bookAppointmentsVM: getIt.get<BookAppointmentsViewModel>(),
                              liveCareClinicsResponseModel: GetLiveCareClinicsResponseModel(),
                              clinicsListResponseModel: GetClinicsListResponseModel(),
                              isLoading: immediateLiveCareVM.isImmediateLiveCareClinicsLoading,
                            )
                          : AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 500),
                              child: SlideAnimation(
                                verticalOffset: 100.0,
                                child: FadeInAnimation(
                                  child: AnimatedContainer(
                                    duration: Duration(milliseconds: 300),
                                    curve: Curves.easeInOut,
                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                    child: LiveCareClinicCard(
                                      immediateLiveCareViewModel: immediateLiveCareVM,
                                      liveCareClinicListResponseModel: immediateLiveCareVM.immediateLiveCareClinicsList[index],
                                      isLoading: immediateLiveCareVM.isImmediateLiveCareClinicsLoading,
                                    ).onPress(() {
                                      if (immediateLiveCareVM.immediateLiveCareClinicsList[index].isOnline == 1) {
                                        onImmediateLiveCareClinicSelected(immediateLiveCareVM.immediateLiveCareClinicsList[index]);
                                      }
                                    }),
                                  ),
                                ),
                              ),
                            );
                    },
                    separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                  ),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

  onImmediateLiveCareClinicSelected(GetLiveCareClinicListResponseModel liveCareClinic) {
    //TODO: add implementation to show clinic schedule
    // if (liveCareClinic.isOnline == 1) {
      showCommonBottomSheetWithoutHeight(context, child: SelectLiveCareCallType(immediateLiveCareViewModel: immediateLiveCareViewModel), callBackFunc: () async {
        if (immediateLiveCareViewModel.liveCareSelectedCallType != 0) {
          immediateLiveCareViewModel.setImmediateLiveCareSelectedClinic(liveCareClinic);
          LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingFeesPleaseWait.tr());
          await immediateLiveCareViewModel.getLiveCareImmediateAppointmentFees(onSuccess: (val) {
            LoaderBottomSheet.hideLoader();
            Navigator.of(context).push(
              CustomPageRoute(
                page: ImmediateLiveCarePaymentDetails(),
              ),
            );
          }, onError: (err) {
            LoaderBottomSheet.hideLoader();
            showCommonBottomSheetWithoutHeight(
              context,
              child: Utils.getErrorWidget(loadingText: err),
              callBackFunc: () {},
              isFullScreen: false,
              isCloseButtonVisible: true,
            );
          });
        }
      }, title: LocaleKeys.selectLiveCareCallType.tr(), isCloseButtonVisible: true, isFullScreen: false);
    // } else {
    //   showCommonBottomSheetWithoutHeight(context,
    //       child: Utils.getErrorWidget(
    //           loadingText: "The selected clinic is only available between ${liveCareClinic.shiftTimings!.first.startTime} & ${liveCareClinic.shiftTimings!.first.endTime} hours."),
    //       callBackFunc: () {},
    //       title: "",
    //       isCloseButtonVisible: true,
    //       isFullScreen: false);
    // }
  }
}
