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/date_util.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/contact_us/contact_us_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/feedback_type.dart';
import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/contact_us/widgets/feedback_appointment_selection.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/image_picker.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';
import 'dart:ui' as ui;

class FeedbackPage extends StatelessWidget {
  FeedbackPage({super.key});

  late ContactUsViewModel contactUsViewModel;
  late MedicalFileViewModel medicalFileViewModel;

  final TextEditingController subjectTextController = TextEditingController();
  final TextEditingController messageTextController = TextEditingController();

  late AppState appState;

  @override
  Widget build(BuildContext context) {
    contactUsViewModel = Provider.of<ContactUsViewModel>(context, listen: false);
    medicalFileViewModel = Provider.of<MedicalFileViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<ContactUsViewModel>(builder: (context, contactUsVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                isLeading: Navigator.canPop(context),
                title: LocaleKeys.feedback.tr(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 16.h),
                    CustomTabBar(
                      activeTextColor: AppColors.primaryRedColor,
                      activeBackgroundColor: AppColors.primaryRedColor.withValues(alpha: .1),
                      tabs: [
                        CustomTabBarModel(null, LocaleKeys.send.tr(context: context)),
                        CustomTabBarModel(null, LocaleKeys.status.tr(context: context)), //TODO: Need to be Disabled This Tab For Now
                      ],
                      onTabChange: (index) {
                        contactUsViewModel.setIsSendFeedbackTabSelected(index == 0);
                      },
                    ).paddingSymmetrical(24.h, 0.h),
                    getSelectedTabWidget(context).paddingSymmetrical(24.h, 16.w),
                  ],
                ),
              ),
            ),
            contactUsViewModel.isSendFeedbackTabSelected
                ? Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      color: AppColors.whiteColor,
                      customBorder: BorderRadius.only(
                        topLeft: Radius.circular(24.h),
                  topRight: Radius.circular(24.h),
                ),
                hasShadow: true,
              ),
              child: CustomButton(
                text: LocaleKeys.submit.tr(context: context),
                onPressed: () async {
                  // Use ViewModel validation method
                  if (!contactUsViewModel.validateFeedbackForm(subjectTextController.text, messageTextController.text)) {
                    // Validation failed, errors are already set in viewModel and displayed below fields
                    return;
                  }

                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.sendingFeedback.tr(context: context));
                  contactUsViewModel.insertCOCItem(
                      subject: subjectTextController.text,
                      message: messageTextController.text,
                      onSuccess: (val) {
                        LoaderBottomSheet.hideLoader();
                        subjectTextController.clear();
                        messageTextController.clear();
                        contactUsViewModel.setPatientFeedbackSelectedAppointment(null);
                        contactUsViewModel.clearAllFeedbackErrors();
                        showCommonBottomSheetWithoutHeight(context, child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr(context: context)), callBackFunc: () {
                          Navigator.pop(context);
                        });
                      },
                      onError: (err) {
                        LoaderBottomSheet.hideLoader();
                        showCommonBottomSheetWithoutHeight(
                          context,
                          child: Utils.getErrorWidget(loadingText: err),
                        );
                      });
                },
                backgroundColor: AppColors.primaryRedColor,
                borderColor: AppColors.primaryRedColor,
                textColor: AppColors.whiteColor,
                fontSize: 16,
                isBold: true,
                borderRadius: 12,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                height: 50.h,
                icon: AppAssets.feedback,
                iconColor: AppColors.whiteColor,
                iconSize: 20.h,
              ).paddingSymmetrical(24.h, 24.h),
                  )
                : SizedBox.shrink(),
          ],
        );
      }),
    );
  }

  Widget getSelectedTabWidget(BuildContext context) {
    if (contactUsViewModel.isSendFeedbackTabSelected) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.likeToHear.tr().toText14(isBold: true),
          SizedBox(height: 16.h),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 16.r,
              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.ask_doctor_icon, width: 24.w, height: 24.h, iconColor: AppColors.greyTextColor),
                        SizedBox(width: 12.w),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            LocaleKeys.feedbackType.tr().toText16(color: AppColors.textColor, isBold: true),
                            (getIt.get<AppState>().isArabic() ? contactUsViewModel.selectedFeedbackType.nameAR : contactUsViewModel.selectedFeedbackType.nameEN)
                                .toText14(color: AppColors.greyTextColor, isBold: true),
                          ],
                        ),
                      ],
                    ),
                    Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                  ],
                ).onPress(() {
                  showCommonBottomSheetWithoutHeight(context,
                      title: LocaleKeys.selectFeedbackType.tr(context: context),
                      child: Container(
                        width: double.infinity,
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24),
                        child: ListView.builder(
                          itemCount: contactUsViewModel.feedbackTypeList.length,
                          physics: NeverScrollableScrollPhysics(),
                          padding: EdgeInsets.only(top: 8, bottom: 8),
                          shrinkWrap: true,
                          itemBuilder: (innerContext, index) {
                            return Theme(
                              data: Theme.of(context).copyWith(
                                listTileTheme: ListTileThemeData(horizontalTitleGap: 4),
                              ),
                              child: RadioListTile<FeedbackType>(
                                title: Text(
                                  getIt.get<AppState>().isArabic() ? contactUsViewModel.feedbackTypeList[index].nameAR : contactUsViewModel.feedbackTypeList[index].nameEN,
                                  style: TextStyle(
                                    fontSize: 16.h,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                value: contactUsViewModel.feedbackTypeList[index],
                                fillColor: WidgetStateProperty.resolveWith((states) {
                                  if (states.contains(WidgetState.selected)) {
                                    return AppColors.primaryRedColor;
                                  }
                                  return Color(0xffEEEEEE);
                                }),
                                contentPadding: EdgeInsets.only(left: 12.h, right: 12.h),
                                groupValue: contactUsViewModel.selectedFeedbackType,
                                onChanged: (FeedbackType? newValue) async {
                                  Navigator.pop(context);
                                  contactUsViewModel.setSelectedFeedbackType(newValue!);
                                  if (contactUsViewModel.selectedFeedbackType.id == 1) {
                                    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingAppointmentsList.tr(context: context));
                                    await medicalFileViewModel.getPatientMedicalReportAppointmentsList(onSuccess: (val) async {
                                      LoaderBottomSheet.hideLoader();
                                      bool? value = await Navigator.of(context).push(
                                        CustomPageRoute(
                                          page: FeedbackAppointmentSelection(),
                                          fullScreenDialog: true,
                                          direction: AxisDirection.down,
                                        ),
                                      );
                                      if (value != null) {
                                        // showConfirmRequestMedicalReportBottomSheet();
                                      }
                                    }, onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: LocaleKeys.noAppointmentsForFeedback.tr(context: context)),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    });
                                  } else {
                                    contactUsViewModel.setPatientFeedbackSelectedAppointment(null);
                                  }
                                },
                              ),
                            );
                          },
                        ),
                      ),
                      callBackFunc: () {},
                      isFullScreen: false,
                      isCloseButtonVisible: true);
                }),
              ]),
            ),
          ),
          if (contactUsViewModel.patientFeedbackSelectedAppointment != null) ...[
            SizedBox(height: 16.h),
            LocaleKeys.selectedAppointment.tr(context: context).toText16(isBold: true),
            SizedBox(height: 8.h),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 20.r,
                hasShadow: false,
              ),
              padding: EdgeInsets.all(16.h),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Utils.buildImgWithNetwork(
                    url: contactUsViewModel.patientFeedbackSelectedAppointment!.doctorImageURL!,
                    iconColor: AppColors.transparent,
                    width: 63.h,
                    height: 63.h,
                    fit: BoxFit.cover,
                  ).circle(100).toShimmer2(isShow: false),
                  SizedBox(width: 16.h),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        (contactUsViewModel.patientFeedbackSelectedAppointment!.doctorNameObj!).toText16(isBold: true, maxlines: 1).toShimmer2(isShow: false),
                        SizedBox(height: 8.h),
                        Wrap(
                          direction: Axis.horizontal,
                          spacing: 3.h,
                          runSpacing: 4.h,
                          children: [
                            AppCustomChipWidget(labelText: contactUsViewModel.patientFeedbackSelectedAppointment!.clinicName!).toShimmer2(isShow: false),
                            AppCustomChipWidget(labelText: contactUsViewModel.patientFeedbackSelectedAppointment!.projectName!).toShimmer2(isShow: false),
                            Directionality(
                              textDirection: ui.TextDirection.ltr,
                              child: AppCustomChipWidget(
                                icon: AppAssets.appointment_calendar_icon,
                                labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(contactUsViewModel.patientFeedbackSelectedAppointment!.appointmentDate), false),
                                      isEnglishOnly: true).toShimmer2(isShow: false),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
          SizedBox(height: 16.h),
          Consumer<ContactUsViewModel>(
            builder: (context, viewModel, child) {
              return TextInputWidget(
                labelText: LocaleKeys.subject.tr(context: context),
                hintText: LocaleKeys.enterSubjectHere.tr(context: context),
                controller: subjectTextController,
                isEnable: true,
                prefix: null,
                autoFocus: false,
                isBorderAllowed: true,
                keyboardType: TextInputType.text,
                hasError: viewModel.subjectError != null,
                errorMessage: viewModel.subjectError,
                onChange: (value) {
                  // Clear error when user starts typing
                  viewModel.clearSubjectError();
                },
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveExtension(10).h,
                  horizontal: ResponsiveExtension(15).h,
                ),
              );
            },
          ),
          SizedBox(height: 16.h),
          Consumer<ContactUsViewModel>(
            builder: (context, viewModel, child) {
              return TextInputWidget(
                labelText: LocaleKeys.message.tr(context: context),
                hintText: LocaleKeys.enterMessageHere.tr(context: context),
                controller: messageTextController,
                isEnable: true,
                prefix: null,
                autoFocus: false,
                isBorderAllowed: true,
                isMultiline: true,
                keyboardType: TextInputType.text,
                hasError: viewModel.messageError != null,
                errorMessage: viewModel.messageError,
                onChange: (value) {
                  // Clear error when user starts typing
                  viewModel.clearMessageError();
                },
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveExtension(10).h,
                  horizontal: ResponsiveExtension(15).h,
                ),
              );
            },
          ),
          SizedBox(height: 16.h),
          CustomButton(
            text: LocaleKeys.selectAttachment.tr(context: context),
            onPressed: () async {
              ImageOptions.showImageOptionsNew(
                context,
                true,
                (String base64Image, file) {
                  // base64Image: The base64-encoded image string
                  // file: The File object
                  contactUsViewModel.addFeedbackAttachment(base64Image, file);
                },
              );
            },
            backgroundColor: AppColors.secondaryLightRedColor,
            borderColor: AppColors.secondaryLightRedColor,
            textColor: AppColors.primaryRedColor,
            fontSize: 14.f,
            isBold: true,
            borderRadius: 10.r,
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            height: 40.h,
            icon: AppAssets.file_icon,
            iconColor: AppColors.primaryRedColor,
            iconSize: 16.h,
          ),
          SizedBox(height: 16.h),
          contactUsViewModel.feedbackAttachmentList.isNotEmpty
              ? Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 12.r,
                    hasShadow: false,
                  ),
                  child: ListView.builder(
                    padding: EdgeInsets.all(16.h),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: contactUsViewModel.feedbackAttachmentList.length,
                    itemBuilder: (BuildContext context, int index) {
                      final attachment = contactUsViewModel.feedbackAttachmentList[index];
                      return Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Icon(
                                  Icons.attach_file,
                                  color: Color(0xff2B353E),
                                ),
                                SizedBox(width: 8.w),
                                Expanded(
                                  child: attachment.fileName.toText14().paddingOnly(bottom: 8.h),
                                ),
                              ],
                            ),
                          ),
                          Utils.buildSvgWithAssets(icon: AppAssets.cancel_circle_icon).onPress(() {
                            contactUsViewModel.removeFeedbackAttachment(attachment);
                          }),
                        ],
                      );
                    },
                  ),
                )
              : SizedBox.shrink(),
        ],
      );
    } else {
      return getIt.get<AppState>().isAuthenticated
          ? Column(
              children: [
                SizedBox(height: 24.h),
                ListView.builder(
                    itemCount: contactUsViewModel.isCOCItemsListLoading
                        ? 4
                        : contactUsViewModel.cocItemsList.isEmpty
                            ? 1
                            : contactUsViewModel.cocItemsList.length,
                    physics: NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    padding: EdgeInsetsGeometry.zero,
                    itemBuilder: (context, index) {
                      return contactUsViewModel.isCOCItemsListLoading
                          ? LabResultItemView(
                              onTap: () {},
                              labOrder: null,
                              index: index,
                              isLoading: true,
                            )
                          : contactUsViewModel.cocItemsList.isNotEmpty
                              ? 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,
                                        child: Container(
                                          padding: EdgeInsets.all(16.h),
                                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                            color: AppColors.whiteColor,
                                            borderRadius: 20.h,
                                            hasShadow: true,
                                          ),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              AppCustomChipWidget(
                                                labelText: appState.isArabic() ? contactUsViewModel.cocItemsList[index].statusAr : contactUsViewModel.cocItemsList[index].status,
                                                // backgroundColor:  AppColors.warningColorYellow,
                                                backgroundColor: (contactUsViewModel.cocItemsList[index].statusId == 7 || contactUsViewModel.cocItemsList[index].statusId == 8)
                                                    ? AppColors.primaryRedColor
                                                    : (contactUsViewModel.cocItemsList[index].statusId == 10 ||
                                                            contactUsViewModel.cocItemsList[index].statusId == 6 ||
                                                            contactUsViewModel.cocItemsList[index].statusId == 9)
                                                        ? AppColors.successColor
                                                        : AppColors.warningColorYellow,
                                                textColor: AppColors.whiteColor,
                                              ),
                                              SizedBox(height: 8.h),
                                              "${LocaleKeys.requestID.tr(context: context)} ${contactUsViewModel.cocItemsList[index].itemID}".toText16(weight: FontWeight.bold),
                                              SizedBox(height: 8.h),
                                              Wrap(
                                                direction: Axis.horizontal,
                                                spacing: 4.h,
                                                runSpacing: 4.h,
                                                children: [
                                                  AppCustomChipWidget(
                                                    labelText: contactUsViewModel.cocItemsList[index].date!.split(" ")[0],
                                                    icon: AppAssets.calendarGrey,
                                                    labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                                                  ),
                                                  AppCustomChipWidget(
                                                    labelText: contactUsViewModel.cocItemsList[index].formType,
                                                    icon: AppAssets.ask_doctor_icon,
                                                    labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                                                  ),
                                                ],
                                              ),
                                              SizedBox(height: 8.h),
                                              "${contactUsViewModel.cocItemsList[index].cOCTitle}"
                                                  .toText16(weight: FontWeight.bold, fontFamily: Utils.isArabicText(contactUsViewModel.cocItemsList[index].cOCTitle ?? "") ? "CairoArabic" : "Poppins"),
                                              SizedBox(height: 8.h),
                                              "${contactUsViewModel.cocItemsList[index].detail}".toText14(
                                                  weight: FontWeight.w600,
                                                  color: AppColors.textColorLight,
                                                  fontFamily: Utils.isArabicText(contactUsViewModel.cocItemsList[index].detail ?? "") ? "CairoArabic" : "Poppins"),
                                            ],
                                          ),
                                        ).paddingOnly(bottom: 16.h),
                                      ),
                                    ),
                                  ),
                                )
                              : Utils.getNoDataWidget(context);
                    }),
              ],
            )
          : Utils.getNoDataWidget(context);
    }
  }
}
