import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:open_store/open_store.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/core/local_storage/local_storage.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
// import 'package:taafee_mobile/core/url%20launcher/url_launcher_service.dart';
import 'package:taafee_mobile/features/auth/business_logic_layer/auth_controller.dart';
// import 'package:taafee_mobile/features/auth/presentation_layer/widgets/tail_auth.dart';
import 'package:taafee_mobile/features/home/business_logic_layer/home_controller.dart';
import 'package:taafee_mobile/features/splash/business_logic_layer/splash_controller.dart';
// import 'package:url_launcher/url_launcher.dart';

import '../../../../common/const/const.dart';
import '../../../../common/widgets/text.dart';
import '../../../../common/widgets/toast.dart';
import '../../../auth/data_layer/model/user.dart';
import '../../../auth/presentation_layer/widgets/tail_auth.dart';

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

  final SplashController splashController = Get.find<SplashController>();
  final AuthController authController = Get.find<AuthController>();
  final HomeController homeController = Get.find<HomeController>();
  final LocalStorage localStorage = LocalStorage();
  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 2), () async {
      await splashController.getParams(
          onConnectionError: (err) {
            Toast.showToast('you_have_no_internet_connection'.tr);
          },
          onSessionTerminated: () async {
            authController.isGuest.update((val) {
              val = false;
            });
            localStorage.saveIsGuest(false);
            String? languangeCode = localStorage.getLanguage();
            await localStorage.clearCache();
            if (languangeCode != null) {
              localStorage.saveLanguage(languangeCode);
            }
            homeController.storage.savefirstTimeOpened();
            RoutingManager.offAll(RouteName.login);
            homeController.selectIndex.value = 0;

            homeController.user.value = User.zero();
          },
          versionAlert: versionAlertDialog);
    });

    return Scaffold(
      body: WillPopScope(
        onWillPop: () async {
          return await splashController.checkVersion(
              versionAlert: versionAlertDialog);
        },
        child: Stack(
          children: [
            Column(
              children: [
                Container().expanded(2),
                SvgPicture.asset('assets/icons/tafee icon.svg'),
                Container().expanded(2),
                const TailAuth().expanded(4),
              ],
            ),
            Center(
              // alignment: Alignment.topCenter,
              child: SizedBox(
                height: Responsive.isTablet() ? 70 : 50,
                child: Obx(() {
                  return Visibility(
                    visible: splashController.showErrorResult.value,
                    child: Center(
                      child: Container(
                        decoration: BoxDecoration(
                          color: AppColors.primeColor,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.signal_wifi_connected_no_internet_4,
                                    color: AppColors.textColor,
                                  ),
                                  const SizedBox(
                                    width: 10,
                                  ),
                                  RegularTextWidget(
                                    '${'you_have_no_internet_connection'.tr} ${'try_again'.tr}',
                                    textAlign: TextAlign.center,
                                    fontSize: Responsive.isTablet() ? 22 : 11,
                                  ).onTap(() async {
                                    await splashController.getParams(
                                        onConnectionError: (err) {
                                          Toast.showToast(
                                              'you_have_no_internet_connection'
                                                  .tr);
                                        },
                                        onSessionTerminated: () async {
                                          authController.isGuest.update((val) {
                                            val = false;
                                          });
                                          localStorage.saveIsGuest(false);
                                          String? languangeCode =
                                              localStorage.getLanguage();
                                          await localStorage.clearCache();
                                          if (languangeCode != null) {
                                            localStorage
                                                .saveLanguage(languangeCode);
                                          }
                                          homeController.storage
                                              .savefirstTimeOpened();
                                          RoutingManager.offAll(
                                              RouteName.login);
                                          homeController.selectIndex.value = 0;

                                          homeController.user.value =
                                              User.zero();
                                        },
                                        versionAlert: versionAlertDialog);
                                  }),
                                ],
                              ),
                            ],
                          ).paddingSymmetric(vertical: 4),
                        ),
                      ),
                    ),
                  );
                }),
              ),
            ).paddingOnly(bottom: Get.height * 0.8).paddingSymmetric(
                  horizontal: Responsive.isTablet() ? 40 : 20,
                ),
          ],
        ),
      ),
    );
  }
}

Future<bool> versionAlertDialog(bool isForced) async {
  bool result = false;
  await Get.defaultDialog(
    onWillPop: () async {
      exit(0);
    },
    barrierDismissible: false,
    title: 'version_update'.tr,
    content: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        RegularTextWidget(
          'new_version_is_available_!'.tr,
          textAlign: TextAlign.center,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container().expanded(1),
            TextButton(
              onPressed: () async {
                result = false;
                OpenStore.instance.open(
                  appStoreId: '284882215',
                  androidAppBundleId: 'com.facebook.katana',
                );
              },
              child: Text('update'.tr),
            ),
            Container().expanded(1),
            if (!isForced)
              TextButton(
                onPressed: () {
                  result = true;
                  RoutingManager.back();
                },
                child: Text('later'.tr),
              ),
            Container().expanded(1),
            if (isForced)
              TextButton(
                onPressed: () {
                  result = false;
                  exit(0);
                },
                child: Text('quit'.tr),
              ),
          ],
        ),
      ],
    ),
  );
  return result;
}
