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/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/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: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;

  static Duration countdownDuration = Duration(minutes: 1, seconds: 0);
  ValueNotifier<Duration> durationNotifier = ValueNotifier<Duration>(countdownDuration);
  Timer? timer;

  @override
  void initState() {
    super.initState();
    scheduleMicrotask(() {
      countdownDuration = Duration(minutes: immediateLiveCareViewModel.patientLiveCareHistoryList[0].watingtimeInteger!, seconds: 0);
      durationNotifier = ValueNotifier<Duration>(countdownDuration);
      startTimer();
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    durationNotifier.dispose();
    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: "LiveCare Pending Request".needTranslation,
                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: [
                              "Expected waiting time: ".toText16(isBold: true),
                              SizedBox(height: 8.h),
                              ValueListenableBuilder<Duration>(
                                valueListenable: durationNotifier,
                                builder: (context, duration, child) {
                                  return Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      buildTime(duration),
                                    ],
                                  );
                                },
                              ),
                              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: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  AppCustomChipWidget(
                                    labelText: immediateLiveCareViewModel.patientLiveCareHistoryList[0].stringCallStatus,
                                    backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.20),
                                    textColor: AppColors.alertColor,
                                  ),
                                  Utils.buildSvgWithAssets(icon: AppAssets.waiting_icon, width: 24.h, height: 24.h),
                                  // 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),
                              "Hala ${appState.getAuthenticatedUser()!.firstName}!!!".needTranslation.toText16(isBold: true),
                              SizedBox(height: 8.h),
                              AppCustomChipWidget(
                                  icon: AppAssets.appointment_calendar_icon,
                                  labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(immediateLiveCareViewModel.patientLiveCareHistoryList[0].arrivalTime), false)),
                              SizedBox(height: 8.h),
                              "Your turn is after ${immediateLiveCareViewModel.patientLiveCareHistoryList[0].patCount} patients.".toText16(isBold: true),
                              SizedBox(height: 8.h),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: true,
              ),
              child: CustomButton(
                text: "Call LiveCare Support".needTranslation,
                onPressed: () async {
                  launchUrl(Uri.parse("tel://" + "011 525 9553"));
                },
                backgroundColor: AppColors.primaryRedColor,
                borderColor: AppColors.primaryRedColor,
                textColor: AppColors.whiteColor,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                borderRadius: 12,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                height: 50.h,
                icon: AppAssets.call_fill,
                iconColor: AppColors.whiteColor,
                iconSize: 21.h,
              ).paddingSymmetrical(24.h, 24.h),
            ),
          ],
        );
      }),
    );
  }

  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.fSize,
            ),
          ),
        ),
      ),
    );
  }

  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,
        ),
      ),
    );
  }
}
