import 'dart:async';

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_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/my_appointments/appointment_via_region_viewmodel.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/doctor_list_api_response.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/faculity_selection/facility_type_selection_widget.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/region_bottomsheet/region_list_widget.dart' show RegionBottomSheetBody;
import 'package:hmg_patient_app_new/presentation/book_appointment/search_doctor_by_name.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/select_clinic_page.dart';
import 'package:hmg_patient_app_new/presentation/lab/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart' show showCommonBottomSheetWithoutHeight;
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart';
import 'package:provider/provider.dart';

import '../appointments/widgets/hospital_bottom_sheet/hospital_bottom_sheet_body.dart';

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

  @override
  State<BookAppointmentPage> createState() => _BookAppointmentPageState();
}

class _BookAppointmentPageState extends State<BookAppointmentPage> {
  late AppState appState;
  late AppointmentViaRegionViewmodel regionalViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      bookAppointmentsViewModel.initBookAppointmentViewModel();
      bookAppointmentsViewModel.getLocation();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(context, listen: true);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.bookAppo.tr(context: context),
        isLeading: Navigator.canPop(context),
        child: SingleChildScrollView(
          child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),
                CustomTabBar(
                  activeTextColor: Color(0xffED1C2B),
                  activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                  tabs: [
                    CustomTabBarModel(null, "General".needTranslation),
                    CustomTabBarModel(null, "LiveCare".needTranslation),
                  ],
                  onTabChange: (index) {
                    bookAppointmentsVM.onTabChanged(index);
                  },
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 24.h),
                getSelectedTabData(bookAppointmentsVM.selectedTabIndex),
              ],
            );
          }),
        ),
      ),
    );
  }

  Widget getSelectedTabData(int index) {
    switch (index) {
      case 0:
        return Column(
          children: [
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: false,
              ),
              child: Padding(
                padding: EdgeInsets.all(16.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_clinic_icon, width: 40.h, height: 40.h),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "Search By Clinic".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500),
                                "Tap to select clinic".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(
                            flipX: appState.isArabic() ? true : false, child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 15.h, height: 15.h)),
                      ],
                    ).onPress(() {
                      bookAppointmentsViewModel.setIsClinicsListLoading(true);
                      bookAppointmentsViewModel.setLoadSpecificClinic(false);
                      bookAppointmentsViewModel.setProjectID(null);
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: SelectClinicPage(),
                        ),
                      );
                    }),
                    SizedBox(height: 16.h),
                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                    SizedBox(height: 16.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_doctor_icon, width: 40.h, height: 40.h),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "Search By Doctor".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500),
                                "Tap to select".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(
                            flipX: appState.isArabic() ? true : false, child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 15.h, height: 15.h)),
                      ],
                    ).onPress(() {
                      bookAppointmentsViewModel.setIsDoctorSearchByNameStarted(false);
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: SearchDoctorByName(),
                        ),
                      );
                    }),
                    SizedBox(height: 16.h),
                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                    SizedBox(height: 16.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.search_by_region_icon, width: 40.h, height: 40.h),
                            SizedBox(width: 12.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "Search By Region".needTranslation.toText14(color: AppColors.textColor, weight: FontWeight.w500),
                                "Central Region".needTranslation.toText12(color: AppColors.primaryRedColor, fontWeight: FontWeight.w500),
                              ],
                            ),
                          ],
                        ),
                        Transform.flip(
                            flipX: appState.isArabic() ? true : false, child: Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon, iconColor: AppColors.textColor, width: 15.h, height: 15.h)),
                      ],
                    ).onPress(() {
                      openRegionListBottomSheet(context);
                    }),
                  ],
                ),
              ),
            ),
          ],
        ).paddingSymmetrical(24.h, 0.h);
      default:
        SizedBox.shrink();
    }
    return Container();
  }

  void openRegionListBottomSheet(BuildContext context) {
    regionalViewModel.flush();
    // AppointmentViaRegionViewmodel? viewmodel = null;
    showCommonBottomSheetWithoutHeight(context,
        title: "",
        titleWidget: Consumer<AppointmentViaRegionViewmodel>(
            builder: (_, data, __) => getTitle(data)),
        isDismissible: false,
        child: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) {
      return getRegionalSelectionWidget(data);
    }), callBackFunc: () {});
  }

  Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data) {
    if (data.bottomSheetState == AppointmentViaRegionState.REGION_SELECTION) {
      return RegionBottomSheetBody();
    }
    if (data.bottomSheetState == AppointmentViaRegionState.TYPE_SELECTION) {
      bookAppointmentsViewModel.resetFilterList();
      return FacilityTypeSelectionWidget(
        selectedRegion: data.selectedRegionId ?? "",
      );
    }
    if (data.bottomSheetState == AppointmentViaRegionState.HOSPITAL_SELECTION) {
      return HospitalBottomSheetBody();
    }
    if (data.bottomSheetState == AppointmentViaRegionState.CLINIC_SELECTION) {
      // Navigator.of(context).pop();
      bookAppointmentsViewModel.setIsClinicsListLoading(true);
      bookAppointmentsViewModel.setLoadSpecificClinic(true);
      bookAppointmentsViewModel.setProjectID(regionalViewModel.selectedHospital?.hospitalList.first?.mainProjectID.toString());
    } else {
      SizedBox.shrink();
    }
    return SizedBox.shrink();
  }

  getTitle(AppointmentViaRegionViewmodel data) {
    if (data.selectedRegionId == null) {
      return LocaleKeys.selectRegion.tr().toText20(weight: FontWeight.w600);
    } else {
      return
        Transform.flip(
          flipX: data.isArabic ? true : false,
          child: Utils.buildSvgWithAssets(
            icon: AppAssets.arrow_back,
            iconColor: Color(0xff2B353E),

            fit: BoxFit.contain,
          ),
        ).onPress(() {
          data.handleBackPress();
        });

    }
  }
}
