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/api_consts.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/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.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/routes/custom_page_route.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

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

  String chatURL = "";

  late AppState appState;
  late AuthenticationViewModel authVm;

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    authVm = context.read<AuthenticationViewModel>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<ContactUsViewModel>(builder: (context, contactUsVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.liveChat.tr(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 16.h),
                    ListView.separated(
                      padding: EdgeInsets.only(top: 16.h),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: contactUsVM.isLiveChatProjectsListLoading ? 5 : contactUsVM.liveChatProjectsList.length,
                      itemBuilder: (context, index) {
                        return contactUsVM.isLiveChatProjectsListLoading
                            ? Container(
                                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                child: Container(
                                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                    color: AppColors.whiteColor,
                                    borderRadius: 20.h,
                                    hasShadow: true,
                                  ),
                                  child: Padding(
                                    padding: EdgeInsets.all(14.h),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Utils.buildImgWithNetwork(
                                              url: "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                                              iconColor: AppColors.transparent,
                                              width: 63.h,
                                              height: 63.h,
                                              fit: BoxFit.cover,
                                            ).circle(100).toShimmer2(isShow: true),
                                            SizedBox(width: 16.h),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  "Dr John Smith".toText16(isBold: true).toShimmer2(isShow: true),
                                                  SizedBox(height: 8.h),
                                                  Wrap(
                                                    direction: Axis.horizontal,
                                                    spacing: 3.h,
                                                    runSpacing: 4.h,
                                                    children: [
                                                      AppCustomChipWidget(labelText: "").toShimmer2(isShow: true, width: 16.h),
                                                      AppCustomChipWidget(labelText: "").toShimmer2(isShow: true, width: 16.h),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ).paddingSymmetrical(24.h, 0.h)
                            : 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: DecoratedBox(
                                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                          color: contactUsVM.selectedLiveChatProjectIndex == index ? AppColors.primaryRedColor : AppColors.whiteColor,
                                          borderRadius: 16.r,
                                          hasShadow: false,
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            ("${appState.isArabic() ? contactUsVM.liveChatProjectsList[index].projectNameN! : contactUsVM.liveChatProjectsList[index].projectName!}"
                                                // "\n${contactUsVM.liveChatProjectsList[index].distanceInKilometers!} KM"
                                            )
                                                .toText14(isBold: true, color: contactUsVM.selectedLiveChatProjectIndex == index ? Colors.white : AppColors.textColor),
                                            Transform.flip(
                                              flipX: getIt.get<AppState>().isArabic(),
                                              child: Utils.buildSvgWithAssets(
                                                icon: AppAssets.forward_arrow_icon_small,
                                                iconColor: contactUsVM.selectedLiveChatProjectIndex == index ? Colors.white : AppColors.textColor,
                                                width: 18.h,
                                                height: 13.h,
                                                fit: BoxFit.contain,
                                              ),
                                            ),
                                          ],
                                        ).paddingSymmetrical(16.h, 16.h),
                                      ).onPress(() {
                                        contactUsVM.setSelectedLiveChatProjectIndex(index);
                                        _getChatRequestID(
                                          context,
                                          contactUsVM,
                                          name: appState.getAuthenticatedUser()!.firstName ?? '',
                                          mobileNo: appState.getAuthenticatedUser()!.mobileNumber ?? '',
                                          workGroup: contactUsVM.liveChatProjectsList[index].value ?? '',
                                        );
                                      }),
                                    ).paddingSymmetrical(24.h, 0.h),
                                  ),
                                ),
                              );
                      },
                      separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                    ),
                    SizedBox(height: 24.h),
                  ],
                ),
              ),
            ),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: true,
              ),
              child: CustomButton(
                text: LocaleKeys.liveChat.tr(context: context),
                onPressed: () async {
                  if(appState.isAuthenticated) {
                    if (contactUsVM.chatRequestID != null) {
                      chatURL = "${ApiConsts.CHAT_URL}${contactUsVM.chatRequestID}";
                      debugPrint("Chat URL: $chatURL");
                      Uri uri = Uri.parse(chatURL);
                      launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
                    } else {
                      debugPrint("Chat Request ID is null");
                    }
                  } else {
                    showCommonBottomSheetWithoutHeight(
                      context,
                      title: LocaleKeys.notice.tr(context: context),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                          SizedBox(height: 8.h),
                          (LocaleKeys.loginToUseService.tr(context: context)).toText16(color: AppColors.blackColor),
                          SizedBox(height: 16.h),
                          Row(
                            children: [
                              Expanded(
                                child: CustomButton(
                                  text: LocaleKeys.cancel.tr(context: context),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  backgroundColor: AppColors.secondaryLightRedColor,
                                  borderColor: AppColors.secondaryLightRedColor,
                                  textColor: AppColors.primaryRedColor,
                                  icon: AppAssets.cancel,
                                  iconColor: AppColors.primaryRedColor,
                                ),
                              ),
                              SizedBox(width: 8.h),
                              Expanded(
                                child: CustomButton(
                                  text: LocaleKeys.confirm.tr(context: context),
                                  onPressed: () async {
                                    Navigator.of(context).pop();
                                    Navigator.pushAndRemoveUntil(
                                        context,
                                        CustomPageRoute(
                                          page: LandingNavigation(),
                                        ),
                                            (r) => false);
                                    await authVm.onLoginPressed();
                                  },
                                  backgroundColor: AppColors.bgGreenColor,
                                  borderColor: AppColors.bgGreenColor,
                                  textColor: Colors.white,
                                  icon: AppAssets.confirm,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 16.h),
                        ],
                      ).center,
                      callBackFunc: () {},
                      isFullScreen: false,
                      isCloseButtonVisible: true,
                    );
                  }
                },
                backgroundColor: contactUsVM.selectedLiveChatProjectIndex == -1 ? AppColors.greyColor : AppColors.primaryRedColor,
                borderColor: contactUsVM.selectedLiveChatProjectIndex == -1 ? AppColors.greyColor : AppColors.primaryRedColor,
                textColor: Colors.white,
                fontSize: 16.f,
                fontWeight: FontWeight.w600,
                borderRadius: 12,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                height: 50.h,
              ).paddingSymmetrical(24.h, 24.h),
            ),
          ],
        );
      }),
    );
  }

  void _getChatRequestID(BuildContext context, ContactUsViewModel contactUsVM, {required String name, required String mobileNo, required String workGroup}) {
    contactUsVM.getChatRequestID(
      name: name,
      mobileNo: mobileNo,
      workGroup: workGroup,
      onSuccess: (response) {
        debugPrint("Chat Request ID received: ${contactUsVM.chatRequestID}");
        chatURL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId=${contactUsVM.chatRequestID}";
        debugPrint("Chat URL: $chatURL");
      },
      onError: (error) {
        debugPrint("Error getting chat request ID: $error");
      },
    );
  }
}
