import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.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/enums.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/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/family_file_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/my_family/widget/family_cards.dart';
import 'package:hmg_patient_app_new/services/dialog_service.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/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

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

  @override
  State<FamilyMedicalScreen> createState() => _FamilyMedicalScreenState();
}

class _FamilyMedicalScreenState extends State<FamilyMedicalScreen> {
  MedicalFileViewModel? medicalVM;

  @override
  void initState() {
    super.initState();
    medicalVM = context.read<MedicalFileViewModel>();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if(medicalVM!.isFamilyFilesLoading) {
        LoaderBottomSheet.showLoader();
      } else {
        LoaderBottomSheet.hideLoader();
      }
      medicalVM?.onFamilyFileTabChange(0);
      medicalVM?.getAllPendingRecordsByResponseId();

    });
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();

    return CollapsingListView(
      isClose: true,
      title: LocaleKeys.familyTitle.tr(context: context),
      bottomChild: appState.getAuthenticatedUser()!.isParentUser!
          ? Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    customBorder: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24)),
                  ),
                  padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 20.h),
                  child: CustomButton(
                      text: LocaleKeys.addANewFamilyMember.tr(context: context),
                      onPressed: () {
                        DialogService dialogService = getIt.get<DialogService>();
                        medicalVM!.clearAuthValues();
                        dialogService.showAddFamilyFileSheet(
                            label: LocaleKeys.addFamilyMember.tr(context: context),
                            message: LocaleKeys.pleaseFillBelowFieldToAddNewFamilyMember.tr(context: context),
                            onVerificationPress: () {
                              medicalVM!.addFamilyFile(otpTypeEnum: OTPTypeEnum.sms);
                            });
                      },
                      icon: AppAssets.add_icon,
                      fontSize: 16.f,
                      borderRadius: 12.r,
                      isBold: true))
              .paddingOnly(bottom: 20.h)
          : SizedBox(),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          appState.isChildLoggedIn
              ? SizedBox()
              : Selector<MedicalFileViewModel, int>(
                  selector: (_, model) => model.getSelectedFamilyFileTabIndex,
                  builder: (context, selectedIndex, child) => CustomTabBar(
                    activeBackgroundColor: AppColors.secondaryLightRedColor,
                    activeTextColor: AppColors.primaryRedColor,
                    // selectedIndex: selectedIndex,
                    tabs: [CustomTabBarModel(null, LocaleKeys.family.tr()), CustomTabBarModel(null, LocaleKeys.request.tr())],
                    onTabChange: (index) {
                      medicalVM!.onFamilyFileTabChange(index);
                    },
                  ),
                ),
          appState.isChildLoggedIn ? SizedBox() : SizedBox(height: 25.h),
          Selector<MedicalFileViewModel, ({int selectedIndex, List<FamilyFileResponseModelLists> patientFiles, List<FamilyFileResponseModelLists> pendingFiles})>(
            selector: (_, model) => (
              selectedIndex: model.getSelectedFamilyFileTabIndex,
              patientFiles: model.patientFamilyFiles,
              pendingFiles: model.pendingFamilyFiles,
            ),
            shouldRebuild: (previous, next) {
              // Only rebuild if something actually changed
              return previous.selectedIndex != next.selectedIndex ||
                     !identical(previous.patientFiles, next.patientFiles) ||
                     !identical(previous.pendingFiles, next.pendingFiles);
            },
            builder: (context, data, child) => getFamilyTabs(
              index: data.selectedIndex,
              patientFiles: data.patientFiles,
              pendingFiles: data.pendingFiles,
            ),
          ),
          SizedBox(height: 20.h),
        ],
      ).paddingSymmetrical(20, 0),
    );
  }

  Widget getFamilyTabs({
    required int index,
    required List<FamilyFileResponseModelLists> patientFiles,
    required List<FamilyFileResponseModelLists> pendingFiles,
  }) {
    switch (index) {
      case 0:

        return FamilyCards(
          profiles: patientFiles,
          onSelect: (FamilyFileResponseModelLists profile) {
            medicalVM!.switchFamilyFiles(responseID: profile.responseId, patientID: profile.patientId, phoneNumber: profile.mobileNumber);
          },
          onRemove: (FamilyFileResponseModelLists profile) {
            medicalVM!.removeFileFromFamilyMembers(id: profile.id);
          },
          isLeftAligned: true,
          isShowDetails: true,
          isShowRemoveButton: true,
        );
      case 1:
        return FamilyCards(
          profiles: pendingFiles,
          isRequestDesign: medicalVM!.getSelectedFamilyFileTabIndex == 1,
          onSelect: (FamilyFileResponseModelLists profile) {
            medicalVM!.acceptRejectFileFromFamilyMembers(id: profile.id, status: 3);
          },
          onRemove: (FamilyFileResponseModelLists profile) {
            medicalVM!.acceptRejectFileFromFamilyMembers(id: profile.id, status: 4);
          },
          isShowDetails: true,
        );
      default:
        return SizedBox.shrink();
    }
  }
}
