import 'dart:io';

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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:in_app_update/in_app_update.dart';
import 'package:lottie/lottie.dart';

class AppUpdatePage extends StatelessWidget {
  AppUpdatePage({super.key, required this.appUpdateMessage});

  final String appUpdateMessage;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.whiteColor,
      body: Column(
        children: [
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(24.h),
              child: Column(
                children: [
                  SizedBox(height: 120.h),
                  Align(
                    alignment: Alignment.topCenter,
                    child: Transform.flip(
                      flipX: getIt.get<AppState>().isArabic() ? true : false,
                      child: Lottie.asset(AppAnimations.onboarding_1,
                          repeat: true, reverse: false, frameRate: FrameRate(60), width: MediaQuery.sizeOf(context).width - 50.w, height: MediaQuery.sizeOf(context).width - 50.w),
                    ),
                  ),
                  SizedBox(height: 50.h),
                  appUpdateMessage.toText16(isBold: true),
                ],
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.r,
              hasShadow: true,
            ),
            child: CustomButton(
              text: LocaleKeys.updateAppNow.tr(context: context),
              onPressed: () {
                openAppUpdateLink();
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              borderRadius: 12.r,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 56.h,
            ),
          ).paddingAll(24.h),
        ],
      ),
    );
  }

  openAppUpdateLink() {
    if (Platform.isAndroid) {
      _handleAndroidAppUpdate();
    }
    if (Platform.isIOS) {
      Utils.openWebView(
        // url: "https://itunes.apple.com/app/id733503978",
        url: "https://itunes.apple.com/app/id6758851027",
      );
    }
  }

  Future<void> _handleAndroidAppUpdate() async {
    const fallbackUrl = "https://play.google.com/store/apps/details?id=com.cloudsolutions.HMGPatientApp";
    try {
      final info = await InAppUpdate.checkForUpdate();
      print("InAppUpdate.checkForUpdate -> $info");

      if (info != null) {
        final immediateAllowed = info.immediateUpdateAllowed ?? false;
        final flexibleAllowed = info.flexibleUpdateAllowed ?? false;

        print("immediateAllowed: $immediateAllowed, flexibleAllowed: $flexibleAllowed");

        if (immediateAllowed) {
          print("Performing immediate update...");
          await InAppUpdate.performImmediateUpdate();
          return;
        }

        if (flexibleAllowed) {
          print("Starting flexible update...");
          await InAppUpdate.startFlexibleUpdate();
          try {
            await InAppUpdate.completeFlexibleUpdate();
          } catch (e) {
            print("Error completing flexible update: $e");
          }
          return;
        }
      }

      print("No in-app update allowed/available; opening Play Store page");
      Utils.openWebView(url: fallbackUrl);
    } catch (e, st) {
      print("InAppUpdate.checkForUpdate threw an exception: $e");
      print(st);
      Utils.openWebView(url: fallbackUrl);
    }
  }
}
