import 'package:didvan/config/design_config.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/main.dart';
import 'package:didvan/providers/media.dart';
import 'package:didvan/providers/server_data.dart';
import 'package:didvan/providers/theme.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:universal_html/html.dart' as html;

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

  @override
  State<Splash> createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  bool _errorOccured = false;
  late ThemeProvider themeProvider;
  late UserProvider userProvider;
  late MediaProvider mediaProvider;

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

    themeProvider = context.read<ThemeProvider>();
    userProvider = context.read<UserProvider>();
    mediaProvider = context.read<MediaProvider>();

    _initialize(themeProvider, userProvider, mediaProvider);
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: DesignConfig.systemUiOverlayStyle.copyWith(
        systemNavigationBarColor: Theme.of(context).colorScheme.background,
      ),
      child: Material(
        child: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 60),
          color: Theme.of(context).colorScheme.background,
          child: Column(
            children: [
              const SizedBox(height: 70),
              SvgPicture.asset(
                Assets.horizontalLogoWithText,
              ),
              if (!_errorOccured)
                Image.asset(
                  Assets.loadingAnimation,
                  width: 60,
                  height: 60,
                ),
              if (_errorOccured) const SizedBox(height: 30),
              if (_errorOccured)
                DidvanButton(
                  width: 120,
                  height: 40,
                  title: 'تلاش مجدد',
                  onPressed: () {
                    setState(() {
                      _errorOccured = false;
                    });
                    _initialize(themeProvider, userProvider, mediaProvider);
                  },
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _initialize(ThemeProvider themeProvider,
      UserProvider userProvider, MediaProvider mediaProvider) async {
    try {
      print("checking if is in browser");
      if (kIsWeb) {
        print("detected browser");
        html.window.onBeforeUnload.listen((event) {
          StorageService.webStorage
              .removeWhere((key, value) => key == 'image-cache');
        });
      }

      final settingsData = await AppInitializer.initilizeSettings();

      themeProvider.themeMode = settingsData.themeMode;
      themeProvider.fontFamily = settingsData.fontFamily;
      themeProvider.fontScale = settingsData.fontScale;

      await AppInitializer.setupServices(navigatorKey.currentContext!);

      final String? token = await userProvider.setAndGetToken();
      print("detected token as $token");

      if (token != null) {
        RequestService.token = token;
        if (!kIsWeb) {
          await mediaProvider.getDownloadsList();
        }

        final result = await userProvider.getUserInfo();

        if (!result) {
          print("no results were returned for user info");
          try {
            StorageService.delete(key: 'token');
          } catch (e) {
            print("error in case of no user info result: $e");
            // catch
          }

          navigatorKey.currentState!.pushNamedAndRemoveUntil(
            Routes.splash,
            (_) => false,
          );

          return;
        }
        print("got results for user info: $result");
        await ServerDataProvider.getData();
      }

      print("token route is $token, initalURI.path: ${initialURI?.path}, intitlPath: ${initialURI?.path}");
      String extractedPath = initialURI?.path.toString() == '/' ? Routes.home : initialURI?.path.toString() ?? Routes.home;
      final String destinationRoute = token == null ? Routes.authenticaion : extractedPath;
      dynamic routeArguments = token == null ? {'isResetPassword': false} : {'showDialogs': true};


      if (destinationRoute == Routes.home) {
        print("destination route was home and init uri is $initialURI");
        // (routeArguments as Map)['deepLinkUri'] = initialURI;
        initialURI = null;
      }

      if(destinationRoute == Routes.authenticaion){
        print("destination route is auth route");
        routeArguments = false;
      }

      print("destination route: $destinationRoute, route args: $routeArguments");
      await navigatorKey.currentState!.pushReplacementNamed(
        destinationRoute,
        arguments: token == null ? false : null,
      );
    } catch (e) {
      setState(() {
        _errorOccured = true;
      });
    }
  }
}