import 'dart:ui' as ui;
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/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/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/countdown_timer.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class ImmediateLiveCarePendingRequestPage extends StatefulWidget {
  ImmediateLiveCarePendingRequestPage({super.key});

  @override
  State<ImmediateLiveCarePendingRequestPage> createState() => _ImmediateLiveCarePendingRequestPageState();
}

class _ImmediateLiveCarePendingRequestPageState extends State<ImmediateLiveCarePendingRequestPage> {
  late ImmediateLiveCareViewModel immediateLiveCareViewModel;

  late AppState appState;
  String chatURL = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // Cancel the timer when leaving the page
    try {
      // immediateLiveCareViewModel.stopTimer();
    } catch (e) {
      // Handle case where viewModel might not be initialized
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    immediateLiveCareViewModel = Provider.of<ImmediateLiveCareViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<ImmediateLiveCareViewModel>(builder: (context, immediateLiveCareVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.livecareAppo.tr(),
                child: Padding(
                  padding: EdgeInsets.all(24.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: false,
                          // side: BorderSide(color: AppColors.ratingColorYellow, width: 3.h),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              LocaleKeys.immediateLiveCareRequest.tr(context: context).toText16(isBold: true),
                              SizedBox(height: 10.h),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Wrap(
                                    children: [
                                      AppCustomChipWidget(
                                        labelText: immediateLiveCareViewModel.patientLiveCareHistoryList.isNotEmpty ? immediateLiveCareViewModel.patientLiveCareHistoryList[0].stringCallStatus : "",
                                        backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.20),
                                        textColor: AppColors.alertColor,
                                      ),
                                      SizedBox(width: 8.w),
                                      AppCustomChipWidget(
                                          icon: AppAssets.appointment_calendar_icon,
                                          labelText: DateUtil.formatDateToDate(
                                              DateUtil.convertStringToDate(
                                                  immediateLiveCareViewModel.patientLiveCareHistoryList.isNotEmpty ? immediateLiveCareViewModel.patientLiveCareHistoryList[0].arrivalTime : ""),
                                              false)),
                                    ],
                                  ),
                                  Container(
                                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                        color: AppColors.greyColor,
                                        borderRadius: 10.h,
                                        hasShadow: false,
                                      ),
                                      padding: EdgeInsets.all(6.h),
                                      child: Lottie.asset(AppAnimations.hourGlass, repeat: true, reverse: false, frameRate: FrameRate(60), width: 40.h, height: 40.h, fit: BoxFit.fill)),
                                  // Lottie.asset(AppAnimations.pending_loading_animation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 80.h, height: 80.h, fit: BoxFit.cover),
                                ],
                              ),
                              SizedBox(height: 8.h),
                              SizedBox(height: 8.h),
                              LocaleKeys.yourTurnIsAfterPatients.tr(namedArgs: {
                                'count': (immediateLiveCareViewModel.patientLiveCareHistoryList.isNotEmpty ? immediateLiveCareViewModel.patientLiveCareHistoryList[0].patCount ?? 0 : 0).toString()
                              }, context: context).toText14(isBold: true),
                              // "Your turn is after ${immediateLiveCareViewModel.patientLiveCareHistoryList[0].patCount} patients.".toText16(isBold: true),
                              SizedBox(height: 8.h),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: false,
                          // side: BorderSide(color: AppColors.ratingColorYellow, width: 3.h),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              LocaleKeys.waitingTime.tr(context: context).toText16(isBold: true),
                              SizedBox(height: 8.h),
                              ValueListenableBuilder<Duration>(
                                valueListenable: immediateLiveCareVM.durationNotifier,
                                builder: (context, duration, child) {
                                  return Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Directionality(textDirection: ui.TextDirection.ltr, child: buildTime(duration)),
                                    ],
                                  );
                                },
                              ),
                              SizedBox(height: 8.h),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 55.h,
                      ),
                      CustomButton(
                        text: LocaleKeys.startLiveChat.tr(),
                        onPressed: () async {
                          // launchUrl(Uri.parse("https://chat.hmg.com/geneysChat/Index.aspx?RequestedId=44A515DF-E668-46B5-BD76-D7747D9C7308"));
                          _getChatRequestID(
                            context,
                            name: appState.getAuthenticatedUser()!.firstName ?? '',
                            mobileNo: appState.getAuthenticatedUser()!.mobileNumber ?? '',
                          );
                        },
                        backgroundColor: AppColors.primaryRedColor,
                        borderColor: AppColors.primaryRedColor,
                        borderWidth: 0,
                        textColor: AppColors.whiteColor,
                        fontSize: 16,
                        isBold: true,
                        isDisabled: !Utils.havePrivilege(118),
                        borderRadius: 12,
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        height: 50.h,
                        icon: AppAssets.livechatMessage,
                        iconColor: !Utils.havePrivilege(118) ? AppColors.textColor : AppColors.whiteColor,
                        iconSize: 21.h,
                      ),
                      SizedBox(
                        height: 16.h,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          LocaleKeys.oR.tr().toText19(
                                color: AppColors.textColor,
                              ),
                        ],
                      ),
                      SizedBox(
                        height: 16.h,
                      ),
                      CustomButton(
                        text: LocaleKeys.callLiveCareSupport.tr(),
                        onPressed: () async {
                          launchUrl(Uri.parse("tel://" + "966 11 525 9553"));
                        },
                        backgroundColor: AppColors.lightRedButtonColor,
                        borderColor: AppColors.lightRedButtonColor,
                        borderWidth: 0,
                        textColor: AppColors.primaryRedColor,
                        fontSize: 16,
                        isBold: true,
                        borderRadius: 12,
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        height: 50.h,
                        icon: AppAssets.call_fill,
                        iconColor: AppColors.primaryRedColor,
                        iconSize: 21.h,
                      )
                    ],
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  void _getChatRequestID(BuildContext context, {required String name, required String mobileNo}) {
    getIt.get<ContactUsViewModel>().getChatRequestID(
          name: name,
          mobileNo: mobileNo,
          workGroup: "Live_Care_Chat",
          onSuccess: (response) {
            debugPrint("Chat Request ID received: ${getIt.get<ContactUsViewModel>().chatRequestID}");
            chatURL = "https://chat.hmg.com/geneysChat/Index.aspx?RequestedId=${getIt.get<ContactUsViewModel>().chatRequestID}";
            debugPrint("Chat URL: $chatURL");
            Uri uri = Uri.parse(chatURL);
            launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
          },
          onError: (error) {
            debugPrint("Error getting chat request ID: $error");
          },
        );
  }

// void startTimer() {
//   // timer = Timer.periodic(const Duration(seconds: 1), (_) => addTime());
//   // setState(() {});
// }
//
// void addTime() {
//   final seconds = durationNotifier.value.inSeconds - 1;
//   if (seconds < 0) {
//     timer?.cancel();
//     // Handle end of timer here
//     // showEndMessage();
//   } else {
//     durationNotifier.value = Duration(seconds: seconds);
//   }
// }
//
// Future<bool> _onWillPop() async {
//   timer?.cancel();
//   Navigator.of(context).pop();
//   return true;
// }
//
// Widget buildTime(Duration duration) {
//   String twoDigits(int n) => n.toString().padLeft(2, '0');
//   final hours = twoDigits(duration.inHours);
//   final minutes = twoDigits(duration.inMinutes.remainder(60));
//   final seconds = twoDigits(duration.inSeconds.remainder(60));
//
//   return Row(
//     mainAxisAlignment: MainAxisAlignment.center,
//     children: [
//       buildTimeColumn(hours, "Hours".needTranslation),
//       buildTimeColumn(minutes, "Mins".needTranslation),
//       buildTimeColumn(seconds, "Secs".needTranslation, isLast: true),
//     ],
//   );
// }
//
// Widget buildTimeColumn(String time, String label, {bool isLast = false}) {
//   return Column(
//     mainAxisAlignment: MainAxisAlignment.center,
//     children: [
//       Row(
//         children: [
//           buildDigit(time[0]),
//           buildDigit(time[1]),
//           if (!isLast) buildTimeSeparator(),
//         ],
//       ),
//       buildLabel(label),
//     ],
//   );
// }
//
// Widget buildDigit(String digit) {
//   return Container(
//     padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
//     // margin: const EdgeInsets.symmetric(horizontal: 2),
//     decoration: BoxDecoration(
//       color: Colors.white,
//       borderRadius: BorderRadius.circular(8),
//     ),
//     child: ClipRect(
//       child: AnimatedSwitcher(
//         duration: const Duration(milliseconds: 600),
//         switchInCurve: Curves.easeOutExpo,
//         switchOutCurve: Curves.easeInExpo,
//         transitionBuilder: (Widget child, Animation<double> animation) {
//           return Stack(
//             children: <Widget>[
//               SlideTransition(
//                 position: Tween<Offset>(
//                   begin: const Offset(0, -1),
//                   end: const Offset(0, 1),
//                 ).animate(CurvedAnimation(
//                   parent: animation,
//                   curve: Curves.easeOutCubic,
//                 )),
//                 child: FadeTransition(
//                   opacity: animation,
//                   child: child,
//                 ),
//               ),
//               SlideTransition(
//                 position: Tween<Offset>(
//                   begin: const Offset(0, -1),
//                   end: const Offset(0, 0),
//                 ).animate(CurvedAnimation(
//                   parent: animation,
//                   curve: Curves.bounceIn,
//                 )),
//                 child: FadeTransition(
//                   opacity: animation,
//                   child: child,
//                 ),
//               ),
//             ],
//           );
//         },
//         child: Text(
//           digit,
//           key: ValueKey<String>(digit),
//           style: TextStyle(
//             fontWeight: FontWeight.bold,
//             color: Colors.black,
//             fontSize: 20.f,
//           ),
//         ),
//       ),
//     ),
//   );
// }
//
// Widget buildLabel(String label) {
//   return label.toText14(isBold: true);
// }
//
// Widget buildTimeSeparator() {
//   return const Padding(
//     padding: EdgeInsets.symmetric(horizontal: 2.0),
//     child: Text(
//       ":",
//       style: TextStyle(
//         color: Colors.black,
//         fontSize: 20,
//       ),
//     ),
//   );
// }
}
